C#:我可以删除 "{ get; set; }"吗?

标签 c#

有区别吗:

public T RequestedValue { get; set; }

public T RequestedValue;

?

取自这段代码:

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

    public T RequestedValue { get; set; }
}

最佳答案

第一个是 Auto-Implemented Property第二个是 Field .常规Properties公开 Getters 和 Setters 但有一个私有(private)字段来实际存储值:

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

第一个允许您更改类实现的某些方面而不影响应用程序中的所有其他代码。最重要的一点是,使用属性,可以在不破坏二进制兼容性的情况下进行更改(尽管通常可以在不破坏代码的情况下将字段更改为属性)。如果是公共(public)成员,建议使用属性。 (无耻地盗用了 Snarfblam 的评论)

从属性页面:

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.

具有支持字段的属性是最灵活的形式,因为它们允许轻松实现诸如 INotifyPropertyChanged 事件之类的东西,用于更新 Model-View-ViewModel 实现中的 UI。

关于C#:我可以删除 "{ get; set; }"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1693875/

相关文章:

c# - 属性或索引器不能作为 out 或 ref 参数传递

c# - WinForms 中的进度条

c# - 压缩webapi POST的正确方法

C# 架构建议 : method to cache data in a structure?

c# - 获取 ConfigurationManager.AppSettings 键名和值

c# - C#中的字节到整数

c# - 如何在有 3 个选项时使用 c# 或 imagemagick 确定文档的背景颜色

c# - 如何在 C# 中替换列表中的值?

c# - 尝试编写一个令人愉快的解析器

c# - 使用 XSP4 在 Monodevelop 中调试 ASP.NET MVC 应用程序