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

前端之家收集整理的这篇文章主要介绍了自动属性在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.

原文链接:https://www.f2er.com/csharp/97562.html

猜你在找的C#相关文章