为何使用带变量的属性 [英] Why Use Property with Variable

查看:71
本文介绍了为何使用带变量的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Code1



Code1

Public Class Person
  Private _name as string
  public property Name  as string
    get
      return _name
    end get
    set(byval value as string)
      _name = value
    end set
  end property
end class



Code 2




Code 2

Public class Person
  Public Property Name as string
end class










If there is no logic in the get/set of the property, why  one write that same property like this:



没有必要设置属性(Code1)

我们可以写代码2

所以为什么我们在c sharp或dotnet中使用属性... .etc


there is no need to set property (Code1)
We Can Write like Code 2
so why we use property in c sharp or dotnet....etc

推荐答案

从逻辑上讲,你是对的。



这是一种编程风格,被认为是同样适合维护:属性要么具有一些getter或setter逻辑,要么可以随时添加此类逻辑而无需更改类/结构接口。通常,它与所有字段应该是私有的规则结合使用,如果没有排除,则可以轻松验证。这意味着具有类似字段接口的所有非私有成员都是属性。



为了实现这种直截了当的属性,更高版本的C#(从v。 3)然后VB.NET引入了自动实现的属性,其中未指定显式支持字段。请参阅:

http://msdn.microsoft.com/en-us /library/bb384054.aspx [ ^ ],

http://msdn.microsoft.com/en -us / library / dd293589.aspx [ ^ ]。



-SA
Logically, you are right.

This is a style of programming which is considered as good for maintenance: the properties either have some getter or setter logic, or such logic could be added anytime without a change in the class/structure interface. Normally, it is used in combination with the rule "all fields should be private", which can be easily validated if there are no exclusion. It means that all non-private members with field-like interface are properties.

To make implementation of such "straightforward" properties, later versions of C# (since v.3) and then VB.NET introduced auto-implemented properties where the explicit backing field is not specified. Please see:
http://msdn.microsoft.com/en-us/library/bb384054.aspx[^],
http://msdn.microsoft.com/en-us/library/dd293589.aspx[^].

—SA


这篇关于为何使用带变量的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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