C#中:我可以删除" {搞定;组; }"? [英] C#: Can I remove "{ get; set; }"?

查看:116
本文介绍了C#中:我可以删除" {搞定;组; }"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有之间的差异:

 公共牛逼RequestedValue {搞定;组; } 

 公共牛逼RequestedValue; ?





这段代码摘自:

 公共类PropertyChangeRequestEventArgs< T>:EventArgs的
{
公共PropertyChangeRequestEventArgs(T pRequestedValue)
{
RequestedValue = pRequestedValue;
}

公共牛逼RequestedValue {搞定;组; }
}


解决方案

第一个是< A HREF =htt​​p://msdn.microsoft.com/en-us/library/bb384054.aspx相对=nofollow>自动实现的属性的第二个是的字段。定期属性暴露getter和setter,但有一个私人领域的实际存储值:

 私人诠释someProperty; 
公众诠释SomeProperty
{
{返回someProperty; }
集合{someProperty =价值; }
}



第一个允许您更改类的实现的某些方面不影响您的应用程序的所有其他代码。最重要的一点是,与特性,可以在不破坏二进制兼容性(虽然场常常可以改变为一个属性不破坏码)来进行变更。如果它是一个公共元件,属性是可取的。的(从Snarfblam的评论无耻地窃取)



在属性页:




属性是成员提供了一个灵活的机制来读取,写入或计算私有字段的值。可使用的属性,如果他们是公共数据成员,但它们实际上是被称为访问特殊的方法。这使得数据可以很容易地访问,仍然有助于促进方法的安全性和灵活性。


与支持字段

属性是最灵活形式,因为它们很容易实现的东西,如 INotifyPropertyChanged的事件更新了模型 - 视图 - 视图模型实现的用户界面。


Is there a difference between:

public T RequestedValue { get; set; }

and

public T RequestedValue;

?

Taken from this code:

public class PropertyChangeRequestEventArgs<T>:EventArgs
{
    public PropertyChangeRequestEventArgs(T pRequestedValue)
    {
        RequestedValue = pRequestedValue;
    }

    public T RequestedValue { get; set; }
}

解决方案

The first is an Auto-Implemented Property the second is a Field. Regular Properties expose Getters and Setters but have a private field to actually store the value:

private int someProperty;
public int SomeProperty
{
    get { return someProperty; }
    set { someProperty = value; }
}

The first allows you to change certain aspects of the implementation of your class without affecting all the other code in your application. The most important point is that, with properties, changes can be made without breaking binary compatibility (although a field can often be changed to a property without breaking code). If it is a public member, a property is advisable. (Stealing shamelessly from Snarfblam's comment)

From the Properties page:

Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Properties with a backing field are the most flexible form as they allow easy implementation of things like the INotifyPropertyChanged event for updating the UI in Model-View-ViewModel implementations.

这篇关于C#中:我可以删除&QUOT; {搞定;组; }&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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