C# 3.0+ 中属性和字段的区别

编程入门 行业动态 更新时间:2024-10-26 14:32:04
本文介绍了C# 3.0+ 中属性和字段的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我意识到它似乎是 C# 中的字段和属性有什么区别? 但我的问题略有不同(从我的角度来看):

I realize that it seems to be a duplicate of What is the difference between a Field and a Property in C#? but my question has a slight difference (from my point of view):

一旦我知道

  • 我不会将我的课程用于仅适用于属性的技术"和
  • 我不会在 getter/setter 中使用验证码.

有什么区别吗(除了样式/未来开发的),比如设置属性时的某种类型的控件?

Is there any difference (except the style/future development ones), like some type of control in setting the property?

是否有任何其他区别:

public string MyString { get; set; }

public string myString;

(我知道,第一个版本需要 C# 3.0 或更高版本,并且编译器会创建私有字段.)

(I am aware that, that the first version requires C# 3.0 or above and that the compiler does create the private fields.)

推荐答案

封装.

在第二个实例中,您刚刚定义了一个变量,在第一个实例中,变量周围有一个 getter/setter.因此,如果您决定以后要验证该变量 - 会容易得多.

In the second instance you've just defined a variable, in the first, there is a getter / setter around the variable. So if you decide you want to validate the variable at a later date - it will be a lot easier.

此外,它们在 Intellisense 中的显示方式不同:)

Plus they show up differently in Intellisense :)

OP 更新问题的更新 - 如果您想忽略此处的其他建议,另一个原因是它根本不是好的 OO 设计.如果您没有充分的理由这样做,总是选择一个属性而不是公共变量/字段.

Update for OPs updated question - if you want to ignore the other suggestions here, the other reason is that it's simply not good OO design. And if you don't have a very good reason for doing it, always choose a property over a public variable / field.

更多推荐

C# 3.0+ 中属性和字段的区别

本文发布于:2023-11-07 17:17:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567011.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   属性   区别

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!