加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:06:31 所属栏目:百科 来源:网络整理
导读:你好朋友. 我的自动属性有一个小问题. 我是一般的编程新手,我只是开始学习类和对象.当我尝试使用自动属性时,该字段不会暴露. (不确定这是不是正确的方式) 在两个动物类中查看属性的注释部分,以了解我在说什么. 现在我有这个动物类 public class Animals{ //f
你好朋友.
我的自动属性有一个小问题.
我是一般的编程新手,我只是开始学习类和对象.当我尝试使用自动属性时,该字段不会暴露. (不确定这是不是正确的方式)
在两个动物类中查看属性的注释部分,以了解我在说什么.

现在我有这个动物类

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读