简体   繁体   English

在C#类中声明公共变量和私有变量的区别

[英]Difference in declaring public and private variables in a C# class

I have an example as follows: 我有一个如下示例:

public static String DocNum
{
    get;
    set;
}

private static String DocNum2;
public static String DocNum2GetSet {
    get
    {
        return DocNum2;
    }
    set
    {
        DocNum2 = value;
    }
}

I was wondering if one declaration benefits the other. 我想知道一个声明是否有益于另一个。 Simple question, hoping for a simple answer. 简单的问题,希望有一个简单的答案。

There is no difference in usage; 用法没有区别; it's just that the first code is neater and therefore easier to write and read. 只是第一个代码更加整洁,因此更易于编写和阅读。 The second code is required if you need to add any extra code, eg validation or raising an event in the setter. 如果您需要添加任何其他代码,例如验证或在setter中引发事件,则需要第二个代码。

In the second case, you are providing consistent API, where you can later modify the underlying structure without having to have consumers change their code. 在第二种情况下,您将提供一致的API,以后您可以在其中修改基础结构,而不必让使用者更改其代码。

For example, right now you are storing DocNum2 in a private string. 例如,现在您正在将DocNum2存储在私有字符串中。 You could later modify this to go get that data from a file or some other resource and the consumer of the code would be none the wiser. 您以后可以修改它,以从文件或其他资源中获取数据,而使用代码的人再合适不过了。

The first example is referred to as an Auto-Implemented Property . 第一个示例称为“ 自动实现的属性” It's shorthand for a full property which is the second of your examples. 这是完整属性的简写,这是您的示例的第二个。 It's valid in C# 3.0 and later . C#3.0及更高版本中有效。

It's often sufficient but if you need custom logic or validation the full property is usually what you'll use. 通常就足够了,但是如果您需要自定义逻辑或验证,通常会使用full属性。 You'll also use the full property when doing things that implement INotifyPropertyChanged . 在执行实现INotifyPropertyChanged时,还将使用full属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM