在其他文件中访问我的公共类时遇到了问题。

huangapple go评论78阅读模式
英文:

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!

huangapple
  • 本文由 发表于 2023年8月9日 03:01:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862502.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定