且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

请告诉我差异

更新时间:2022-10-20 07:57:20

通过一种方法,您可以在属性集/ get中获得验证或其他代码。另一种方式是简单地设置或获取属性而不需要额外的代码。



Microsoft帮助文件解释了差异:



使用属性(C#编程指南 [ ^ ]

属性有许多用途:它们可以在允许更改之前验证数据;它们可以透明地公开数据,这些数据实际上是从某些其他来源(例如数据库)检索数据;它们可以在执行时执行操作数据被更改,例如引发事件或更改其他字段的值。



自动实现的属性(C#编程指南) [ ^ ]

当属性访问器中不需要额外的逻辑时,自动实现的属性使属性声明更简洁。它们还使客户端代码能够创建对象。声明属性时,编译器会创建一个私有的匿名支持字段,只能通过属性的get和set访问器访问。


Hi


你的第一个代码说明了带有属性的字段封装,第二个代码是auto属性,当你使用属性封装字段时,你可以在属性中写一些代码来控制 value 然后绑定现场和另外:



1 - 你可以将数据绑定到一个字段,而你可以到一个属性

2 - 如果你开始使用一个字段,你可以稍后(轻松)将它们更改为一个属性

3 - 你可以添加一些属性,你不能添加到一个字段

4-Fields不能用于数据绑定(至少在某些绑定实现中)

5 - 您可以稍后为属性添加更多逻辑,而不会破坏源或二进制兼容性

6 - 属性不能通过referen传递ce

7 - 您无法为自动实施的属性添加初始化方法





***的问候

This is a property which is encapsulated below:

int _CategoryID;

   public int CategoryID
        {
            get
            {
                return _CategoryID;
            }
            set
            {
                _CategoryID = value;
            }
        }



and other is direct get set in the variable like :

public int CategoryID { set; get; }




So my question is that , what is difference between in both and what shoud we use or recommended?
Are they same ?

please let me know about it...

One way lets you have validation or other code in the property set/get. The other way simply sets or gets the property with no additional code.

The Microsoft Help file explains the differences:

Using Properties (C# Programming Guide[^]
Properties have many uses: they can validate data before allowing a change; they can transparently expose data on a class where that data is actually retrieved from some other source, such as a database; they can take an action when data is changed, such as raising an event, or changing the value of other fields.

Auto-Implemented Properties (C# Programming Guide)[^]
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, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.


Hi
Your first code illustrate field encapsulation with property and second code is auto property when you are use property for encapsulate field you can write some codes in property for control value before than binding to field and additionally:

1-You can`t data bind to a field whereas you can to a property
2-If you start off using a field, you can`t later (easily) change them to a property
3-There are some attributes that you can add to a property that you can`t add to a field
4-Fields can't be used in data binding (at least in some binding implementations)
5-You can add more logic later for properties without breaking source or binary compatibility
6-Properties can't be passed by reference
7-You can't add an initialization method to an automatically implemented property


Best Regards.