C# .NET 中的 Getter 和 Setter 声明
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17881091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getter and Setter declaration in .NET
提问by WizLiz
I was wondering what were the differences between those declaration of getters and setters and if there is a preferred method (and why). The first one can be generated automaticly by Visual Studio. How about the others ? Thanks
我想知道 getter 和 setter 的这些声明之间有什么区别,以及是否有首选方法(以及为什么)。第一个可以由 Visual Studio 自动生成。其他人呢?谢谢
1st
第一
string _myProperty { get; set; }
2nd
第二
string _myProperty;
public string myProperty
{
get { return _myProperty; }
set { _myProperty = value; }
}
3rd
第三名
string _myProperty;
public string getMyProperty()
{
return this._myProperty;
}
public void setMyProperty(string value)
{
this._myProperty = value;
}
采纳答案by Wouter de Kort
Properties are used to encapsulate some data. You could use a plain field:
属性用于封装一些数据。您可以使用普通字段:
public string MyField
But this field can be accessed by all outside users of your class. People can insert illegal values or change the value in ways you didn't expect.
但是您班级的所有外部用户都可以访问此字段。人们可以插入非法值或以您意想不到的方式更改值。
By using a property, you can encapsulate the way your data is accessed. C# has a nice syntax for turning a field into a property:
通过使用属性,您可以封装访问数据的方式。C# 有一个很好的语法可以将字段转换为属性:
string MyProperty { get; set; }
This is called an auto-implemented property. When the need arises you can expand your property to:
这称为自动实现的属性。当需要时,您可以将您的财产扩展到:
string _myProperty;
public string MyProperty
{
get { return _myProperty; }
set { _myProperty = value; }
}
Now you can add code that validates the value in your setter
:
现在,您可以添加验证您的值的代码setter
:
set
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentNullException();
_myProperty = value;
}
Properties can also have different accessors for the getter and the setter:
属性也可以有不同的 getter 和 setter 访问器:
public string MyProperty { get; private set; }
This way you create a property that can be read by everyone but can only be modified by the class itself.
通过这种方式,您可以创建一个所有人都可以读取但只能由类本身修改的属性。
You can also add a completely custom implementation for your getter
:
您还可以为您的getter
:添加一个完全自定义的实现:
public string MyProperty
{
get
{
return DateTime.Now.Second.ToString();
}
}
When C# compiles your auto-implemented property, it generates Intermediate Language (IL). In your IL you will see a get_MyProperty
and set_MyProperty
method. It also creates a backing field called <MyProperty>k_BackingField
(normally this would be an illegal name in C# but in IL it's valid. This way you won't get any conflicts between generated types and your own code). However, you should use the official property syntax in C#. This creates a nicer experience in C# (for example with IntelliSense).
当 C# 编译自动实现的属性时,它会生成中间语言 (IL)。在您的 IL 中,您将看到一个get_MyProperty
andset_MyProperty
方法。它还创建了一个名为的支持字段<MyProperty>k_BackingField
(通常这在 C# 中是非法名称,但在 IL 中它是有效的。这样您就不会在生成的类型和您自己的代码之间产生任何冲突)。但是,您应该使用 C# 中的官方属性语法。这在 C# 中创建了更好的体验(例如使用 IntelliSense)。
By convention, you shouldn't use properties for operations that take a long time.
按照惯例,您不应将属性用于需要很长时间的操作。
回答by Mike Perrenoud
Well, the first and second both generate something likethe third in the end. However, don't use the third when you have a syntax for properties.
好吧,第一个和第二个最终都会生成类似于第三个的东西。但是,当您有属性语法时,不要使用第三个。
Finally, if you have no work to do in the get
or set
, then use the first.
最后,如果您在get
or 中没有工作要做set
,则使用第一个。
In the end, the first and second are just some form of syntactic sugar, but why code more than what's necessary.
最后,第一个和第二个只是某种形式的语法糖,但为什么要编写比必要的更多的代码。
// more code == more bugs
And just to have a little fun, consider this:
只是为了玩得开心,请考虑一下:
public string A { get; private set; }
Now that's a lot more straight forward isn't it? The public
modifier is impliedon both the get
and the set
, but it can be overriden. This would of course be the same rule for any modifier used when defining the property itself.
现在这更直接了,不是吗?该public
修饰符暗示双方的get
和set
,但它可以被覆盖。对于定义属性本身时使用的任何修饰符,这当然是相同的规则。
回答by NG.
The 1st one is default, when there is nothing special to return or write. 2nd and 3rd are basically the same where 3rd is a bit more expanded version of 2nd
第一个是默认的,当没有什么特别的返回或写入时。2nd 和 3rd 基本相同,其中 3rd 是 2nd 的扩展版本
回答by DarthVader
Lets start with 3. That wouldnt work. public getMyProperty()
has no return typ.
让我们从 3 开始。那行不通。public getMyProperty()
没有返回类型。
And number 1 and 2 are actually same things. 2 is what number 1 becomes after compilation.
1 号和 2 号实际上是相同的东西。2 是编译后的数字 1。
So 1 and 2 are same things. with two you can have some validation or caching in your model.
所以1和2是一样的东西。使用两个,您可以在模型中进行一些验证或缓存。
other than that they become same.
除此之外,它们变得相同。
回答by Felipe Oriani
With this, you can perform some code in the get
or set
scope.
有了这个,您可以在get
orset
范围内执行一些代码。
private string _myProperty;
public string myProperty
{
get { return _myProperty; }
set { _myProperty = value; }
}
You also can use automatic properties:
您还可以使用自动属性:
public string myProperty
{
get;
set;
}
And .Net Framework will manage for you. It was create because it is a good pratice and make it easy to do.
.Net Framework 将为您管理。它之所以被创造,是因为它是一种很好的做法,而且很容易做到。
You also can control the visibility of these scopes, for sample:
您还可以控制这些范围的可见性,例如:
public string myProperty
{
get;
private set;
}
public string myProperty2
{
get;
protected set;
}
public string myProperty3
{
get;
}
Update
更新
Now in C# you can initialize the value of a property. For sample:
现在在 C# 中,您可以初始化属性的值。样品:
public int Property { get; set; } = 1;
If also can define it and make it readonly, without a set.
如果也可以定义它并使其成为只读的,没有设置。
public int Property { get; } = 1;
And finally, you can define an arrow function.
最后,您可以定义一个箭头函数。
public int Property { get; } => GetValue();
回答by Christian Sauer
The first one is the "short" form - you use it, when you do not want to do something fancy with your getters and setters. It is not possible to execute a method or something like that in this form.
第一个是“短”形式——当你不想对你的 getter 和 setter 做一些花哨的事情时,你可以使用它。不可能以这种形式执行方法或类似的东西。
The second and third form are almost identical, albeit the second one is compressed to one line. This form is discouraged by stylecop because it looks somewhat weird and does not conform to C' Stylguides.
第二种和第三种形式几乎相同,尽管第二种形式被压缩为一行。stylecop 不鼓励这种形式,因为它看起来有些奇怪并且不符合 C' Stylguides。
I would use the third form if I expectd to use my getters / setters for something special, e.g. use a lazy construct or so.
如果我希望将我的 getter/setter 用于特殊的东西,例如使用惰性构造等,我会使用第三种形式。
回答by Andrew Grothe
1st
第一
string _myProperty { get; set; }
This is called an Auto Propertyin the .NET world. It's just syntactic sugar for #2.
这在 .NET 世界中称为自动属性。这只是#2 的语法糖。
2nd
第二
string _myProperty;
public string myProperty
{
get { return _myProperty; }
set { _myProperty = value; }
}
This is the usual way to do it, which is required if you need to do any validation or extra code in your property. For example, in WPF if you need to fire a Property Changed Event. If you don't, just use the auto property, it's pretty much standard.
这是通常的做法,如果您需要在您的财产中进行任何验证或额外的代码,则这是必需的。例如,在 WPF 中,如果您需要触发属性更改事件。如果你不这样做,只需使用 auto 属性,它几乎是标准的。
3
3
string _myProperty;
public string getMyProperty()
{
return this._myProperty;
}
public string setMyProperty(string value)
{
this._myProperty = value;
}
The this
keyword here is redundant. Not needed at all. These are just Methods that get and set as opposed to properties, like the Java way of doing things.
this
这里的关键字是多余的。根本不需要。这些只是 get 和 set 的方法,而不是属性,就像 Java 的做事方式一样。
回答by OnABauer
Just to clarify, in your 3rd example _myProperty isn't actually a property. It's a field with get and set methods (and as has already been mentioned the get and set methods should specify return types).
澄清一下,在你的第三个例子中 _myProperty 实际上不是一个属性。它是一个带有 get 和 set 方法的字段(正如已经提到的,get 和 set 方法应该指定返回类型)。
In C# the 3rd method should be avoided in most situations. You'd only really use it if the type you wanted to return was an array, or if the get method did a lot of work rather than just returning a value. The latter isn't really necessary but for the purpose of clarity a property's get method that does a lot of work is misleading.
在 C# 中,在大多数情况下应该避免使用第三种方法。如果您想要返回的类型是数组,或者如果 get 方法做了很多工作而不仅仅是返回一个值,您才会真正使用它。后者并不是真正必要的,但为了清楚起见,执行大量工作的属性的 get 方法具有误导性。