道具和完整财产有什么区别? [英] What is the difference between prop and a full property?

查看:64
本文介绍了道具和完整财产有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的两段代码之间有什么区别吗?还是顶部只是底部的简短形式?

Is there any difference between the two pieces of code below? Or is the top just a short form of the bottom one?

public string Name { get; set; }

private string _Name;
public string Name
{
    get { return _Name; }
    set { _Name = value; }
}

推荐答案

唯一的区别(除了您必须在类构造函数中使用默认名称"进行初始化的事实以外)是 _Name 将在类本身内可见.该类可能会在内部引用 _Name 而不是 Name ,这一切都会正常工作,稍后您将在中添加一些逻辑名称,因为在类中使用的是 _Name ,所以不会被调用.

The only difference (other than the fact you would have to do the initialization with "Default Name" in your class constructor) is that _Name will be visible within the class itself. There's a risk that the class will internally reference _Name rather than Name, everything will work fine, and at some later point in time you'll add some logic to Name that will not be called because you're using _Name within the class.

示例:

private string _Name = "Default Name";
public string Name
{
   get { return _Name.Left(42); }  // Changed the getter
   set { _Name = value; }
}

void MyOtherMethod()
{
   string foo = _Name; // Referencing the private field accidentally instead of the public property.
   // Do something with foo
}

这篇关于道具和完整财产有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆