自动属性在c#中不起作用

你好朋友.
我的自动属性一个小问题.
我是一般的编程新手,我只是开始学习类和对象.当我尝试使用自动属性时,该字段不会暴露. (不确定这是不是正确的方式)
在两个动物类中查看属性的注释部分,以了解我在说什么.

现在我有这个动物类

public class Animals
{
    //fields
    private string name;

    public Animals(string name)
    {
        this.name = name;
    }

    // default constructor
    public Animals()
    { }

    //This is the problematic portion
    public string Name { get; set; }


    public void Bark()
    {
        Console.WriteLine("{0} said WoWOW",name);
    }

}

这是我的主要课程

class Program
{
    static void Main(string[] args)
    {

        Console.WriteLine("Enter name: ");
        string name = Console.ReadLine();
        Animals dog = new Animals(name);
        dog.Bark();

        Animals cat = new Animals();
        Console.WriteLine("Enter second name: ");
        cat.Name = Console.ReadLine();
        cat.Bark();


    }
}

输出如下.最后一行是我的问题

Enter name:
    bob
    bob said WoWOW
    Enter second name:
    Sarah
     said WoWOW //Sarah is missing here

但是,当我将属性从{get; set}更改为类中的完整版本时.它输出正确的输出.

编辑的代码

public class Animals
{
    //fields
    private string name;

    public Animals(string name)
    {
        this.name = name;
    }

    public Animals()
    { }

    //apparently this is the correct way of making properties
    public string Name
    {
        get { return name; }
        set { name = value; }
    }


    public void Bark()
    {
        Console.WriteLine("{0} said WoWOW",name);
    }

}

output:// Sarah出现在最后一行

Enter name:
    bob
    bob said WoWOW
    Enter second name:
    Sarah
    Sarah said WoWOW

我的问题是:为什么在使用自动属性时我没有得到我想要的输出但是当我完全写出属性时,我确实得到了我想要的结果.
谢谢你看看我的问题.希望它不会太久! ]

解决方法

这将有效:
public class Animals
{
    //fields
    private string name; // <-- You don't need it when you have auto properties

    public Animals(string name)
    {
        Name = name;// <-- Using auto property
    }

    public string Name { get; set; }

    public void Bark()
    {
        Console.WriteLine("{0} said WoWOW",Name);//<-- Using auto property
    }

}

另外,你应该看看What are Automatic Properties in C# and what is their purpose?Auto-Implemented Properties (C# Programming Guide)

旁注1:如果没有其他构造函数,则无参数的空公共构造函数是无用的.正如Joe指出的那样,如果在你的例子中你删除它,你将无法调用var a = new Animals();

旁注2:用一个单数名词命名你的类是很常见的,这里是Animal.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...