从未分配的c#字段的默认值为0

时间:2017-05-25 18:32:24

标签: c#

刚开始使用课程。我的int age无法使用我的房产Age。它总是0。

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Stuffers s = new Stuffers("Stuffy McStuff");
        }
    }

    class Stuffers
    {
        private int age;
        public int Age
        {
            get { return age; } set { value = age; }
        }
    }
}       

显示错误:

  

从未分配过字段时间,默认值为0

原始非MCVE代码

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Stuffers s = new Stuffers("Stuffy McStuff");
            Console.WriteLine(s.GetName());

            Console.Write("{0}, what is your age?", s.GetName());
            s.Age = Convert.ToInt32(Console.ReadLine());

            Stuffers s2 = new Stuffers("Leeroy");
            Console.WriteLine(s.GetAge());
        }
    }

    class Stuffers
    {
        private int age;
        private string name;
        public int Age
        {
            get { return age; } set { value = age; }
        }
        public Stuffers(string nameC)
        {
            name = nameC;
        }
        public string GetName()
        {
            return name;
        }
        public int GetAge()
        {
            return age;
        }
    }
}       

2 个答案:

答案 0 :(得分:5)

这是错误的:

public int Age
{
    get { return age; } set { value = age; }
}

应该是:

public int Age
{
    get { return age; } set { age = value; }
}

value是您要分配的新值。 age是管家变量。

或者,您可以这样做:

public int Age { get; set; }

未声明age

此外,GetAge()方法似乎是多余的,将GetName转换为只获取属性可能更好:

class Stuffers
{
    public int Age
    {
        get; set;
    }
    public string Name { get; private set; }
    public Stuffers(string nameC)
    {
        Name = nameC;
    }
}

答案 1 :(得分:2)

您没有将年龄设置为值

更改此

public int Age
{
    get { return age; } set { value = age; }
}

到此

public int Age
{
    get { return age; } set { age = value; }
}