c# - C# 中的属性

标签 c# properties accessor

我们为什么能写

public int RetInt
{
   get;set;
}

代替

public int RetInt
{
   get{return someInt;}set{someInt=value;}
}

两者有什么区别?

最佳答案

此功能称为 Auto implemented properties并在 C# 3.0 中引入

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

class Customer
{
    // Auto-Impl Properties for trivial get and set 
    public double TotalPurchases { get; set; }
    public string Name { get; set; }
    public int CustomerID { get; set; }

针对您的问题

What is the difference between the two?

在你的情况下,没有。由于您在设置或检索值时没有做任何事情,但假设您想要进行一些验证或想要执行其他类型的检查:

private int someInt;
public int RetInt
{
    get
    {
        if (someInt > 0)
            return someInt;
        else
            return -1;
    }
    set { someInt = value; } // same kind of check /validation can be done here
}

以上不能用自动实现的属性来完成。

您可以看到不同之处的另一件事是在初始化自定义类类型属性时。

如果你有 MyClass 列表 然后在 Normal 属性的情况下,除了构造函数之外,它的支持字段可以被初始化/实例化。

private List<MyClass> list = new List<MyClass>();
public List<MyClass> List
{
    get { return list; }
    set { list = value; }
}

如果是自动实现的属性,

public List<MyClass> SomeOtherList { get; set; }

您只能在构造函数中初始化SomeOtherList,不能在Field 级别执行此操作。

关于c# - C# 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14559909/

相关文章:

c# - objects.GetObject(i) 比 objects[i] 有什么优势?

c# - 交互服务与交互请求对象

c# - 通过另一个条件更改 LINQ 中的条件

c# - 什么时候应该使用 using 语句?

javascript - Datagrid 相当于 HTML 表单占位符属性

C# 属性,是否可以绕过定义 get 而不定义 set(无支持变量)?

properties - .properties 文件的 log4j2 KeyValuePair

c++ - 在 Arduino 中使用访问器方法传递数据

PHP - 如何重命名对象属性?

java - List 的类属性类型,不可由访问器修改