如何在C#3.0中自定义自动属性

时间:2022-09-02 08:46:17

Before C# 3.0 we done like this:

在C#3.0之前,我们这样做:

class SampleClass
{
   private int field;
   public int Property { get { return this.field } set { this.field = value } }
}

Now we do this:

现在我们这样做:

class SampleClass
{
   public int Property { get; set; }
}

(Look ma! no fields!) Now if I want to customize the Getter or the Setter, the field must be explicit as it was in C#2.0?

(看看ma!没有字段!)现在,如果我想自定义Getter或Setter,那么该字段必须是C#2.0中的显式字符?

4 个解决方案

#1


Yes, that's the only way. No shortcut for customization (other than access modifiers).

是的,这是唯一的方法。没有自定义的快捷方式(访问修饰符除外)。

#2


With C# 3.0 and automatic properties, you can still change the access levels:

使用C#3.0和自动属性,您仍然可以更改访问级别:

class SampleClass
{
   public int Property { get; private set; }
}

#3


Yeah, the purpose of the automatic properties is provide a means to add customizations in the future, without affecting existing users of the class. This usually means adding a private/protected backing field.

是的,自动属性的目的是提供一种在将来添加自定义的方法,而不会影响该类的现有用户。这通常意味着添加私有/受保护的支持字段。

#4


You also cannot specify readonly fields using automatic properties, nor can you use variable initializers (although I have seen a few suggested language extensions that would allow those).

您也不能使用自动属性指定只读字段,也不能使用变量初始值设定项(尽管我已经看到了一些允许这些的建议语言扩展)。

You can make automatic properties virtual, but that means that any access to the property in the class could call subtype implementations instead.

您可以将自动属性设置为虚拟,但这意味着对类中属性的任何访问都可以调用子类型实现。

#1


Yes, that's the only way. No shortcut for customization (other than access modifiers).

是的,这是唯一的方法。没有自定义的快捷方式(访问修饰符除外)。

#2


With C# 3.0 and automatic properties, you can still change the access levels:

使用C#3.0和自动属性,您仍然可以更改访问级别:

class SampleClass
{
   public int Property { get; private set; }
}

#3


Yeah, the purpose of the automatic properties is provide a means to add customizations in the future, without affecting existing users of the class. This usually means adding a private/protected backing field.

是的,自动属性的目的是提供一种在将来添加自定义的方法,而不会影响该类的现有用户。这通常意味着添加私有/受保护的支持字段。

#4


You also cannot specify readonly fields using automatic properties, nor can you use variable initializers (although I have seen a few suggested language extensions that would allow those).

您也不能使用自动属性指定只读字段,也不能使用变量初始值设定项(尽管我已经看到了一些允许这些的建议语言扩展)。

You can make automatic properties virtual, but that means that any access to the property in the class could call subtype implementations instead.

您可以将自动属性设置为虚拟,但这意味着对类中属性的任何访问都可以调用子类型实现。