英文:
Having a problem with accessing my public class in other files
问题
我正在尝试从一本书中学习C#,并且我正在尝试从这个文件中访问我的公共类:
public class Character
{
public string name;
public int exp = 0;
public Character(string name)
{
this.name = name;
}
}
在这个文件中:
public class HeroInfo : MonoBehaviour
{
void Start()
{
Character hero = new Character();
Debug.LogFormat("Hero: {0} - Experience {1}", hero.name, hero.exp);
}
}
在第二个文件中,当我尝试访问"Character"时,它根本没有显示出来,导致我无法使用它。
我期望"Character"在第二个文件中可以作为一个变量被访问,但是显然它并没有起作用。
如果我没有正确格式化这篇文章,我很抱歉,这是我在这个网站上的第一篇帖子,也可能不是最后一篇。
英文:
I'm trying to learn C# from a book and I'm trying to access my public class from this file:
public class Character
{
public string name;
public int exp = 0;
public Character(string name)
{
this.name = name;
}
}
in this file:
public class HeroInfo : MonoBehaviour
{
void Start()
{
Character hero = new Character();
Debug.LogFormat("Hero: {0} - Experience {1}", hero.name, hero.exp);
}
}
In the second file when I try to access "Character", it doesn't show up at all making me unable to use it.
I expected for "Character" to be accessible in the second file as a variable, yet as visible, it didn't really work.
I'm sorry if I didn't format this post properly, yet it's my first and probably not last post on this site.
答案1
得分: 2
你错过了一个默认构造函数。以下是如何修复它的方法:
public class Character
{
// 添加一个默认构造函数
public Character() {}
public Character(string name)
{
this.name = name;
}
}
或者你可以在使用时传递 name
参数:Character hero = new Character("some name");
。
英文:
You've missed a default constructor. Here how you can fix it:
public class Character
{
// Add a default constructor
public Character() {}
public Character(string name)
{
this.name = name;
}
}
Or you should use it passing the name
parameter: Character hero = new Character("some name");
.
答案2
得分: 1
在第二个文件的顶部,你需要添加第一个文件的命名空间 - 应该是包含你的Character类的文件。
然后最好也创建一个空构造函数!
英文:
On the top of the second file you need to add the namespace of the first file - should be the file that contains your Character class.
Then is better if you also create the empty constructor!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论