简体   繁体   English

.net 中的 readonly 属性和函数有什么区别?

[英]What is the difference between readonly property and function in .net?

Apart from an architectural point of view, i'm wondering if there is any difference in .net between a readonly property and a function.除了从架构的角度来看,我想知道 .net 中的只读属性和函数之间是否有任何区别。 Are properties only conceptual wrappers around functions?属性只是函数的概念包装吗?

    Private m_Property As String 
    Public ReadOnly Property PropertyGet() As String
        Get
            Return m_Property
        End Get
    End Property

    Public Function FunctionGet() As String
        Return m_Property
    End Function

Disassembling IL shows that there's no difference apart from the name, but are there differences at another level?反汇编IL,除了名字没有区别,但在另一个层面上有区别吗? Is the getter just a function in short(!?)hand? getter 只是简而言之(!?)的一个函数吗?


Edit : wow, i'm really sorry about not being able to mark multiple answers. Edit :哇,我真的很抱歉无法标记多个答案。

The first answer that pointed out the use of properties to serialize was the road to enlightenment since i had completely left this aspect out.指出使用属性进行序列化的第一个答案是启蒙之路,因为我完全忽略了这方面。 Before that, the explanation of property vs function as "is" vs "does" felt arbitrary.在此之前,将属性与功能解释为“是”与“确实”是随意的。 Now, i grok it more.现在,我更了解它。

I think the consensus on property being not time consuming stems from the "is"/serializable concept.我认为关于财产不耗时的共识源于“是”/可序列化的概念。 If my property talks to a database to store the "is" value, it breaks in horrible ways.如果我的属性与数据库通信以存储“is”值,它会以可怕的方式中断。

The difference is more semantic that functional;区别在语义上比功能上更重要; a property getter is in fact a function under the hood.属性 getter 实际上是引擎盖下的函数。 The difference is more that as a programmer, you often expect that calling a property getter is a very cheap operation, while calling a function could potentially be more expensive.不同之处在于,作为程序员,您经常期望调用属性 getter 是一种非常便宜的操作,而调用函数可能会更昂贵。

Note that this is not necessarily the case;请注意,情况并非一定如此; you can very well implement very light-weight functions, and very heavy property getters, but as a rule of thumb, a property getter should typically do nothing much more than simply get the value.你可以很好地实现非常轻量级的函数和非常重的属性 getter,但根据经验,属性 getter 通常应该只做简单的获取值。

如果您使用数据绑定,则有一个重要区别,您根本无法绑定到方法,只能绑定到属性。

The whole property thing was - probably - conceived to avoid getting a bunch of separate GetSomething(), SetSomething(var x) methods, which used to be the norm in, for example, Java in the early 2000s for data access.整个属性的设计——可能——是为了避免获得一堆单独的 GetSomething()、SetSomething(var x) 方法,这些方法曾经是 2000 年代早期 Java 中用于数据访问的规范。 This to avoid publicly exposed variables.这是为了避免公开暴露的变量。

Believe me, those classes looked awful.相信我,那些课程看起来很糟糕。 I personally think the property concept is a great leap forward in readability and structure.我个人认为属性概念在可读性和结构上是一个巨大的飞跃。

A property combines both concepts of fields and methods.属性结合了字段和方法的概念。 In fact, a property is accesed like a field, but the underlying pieces of code are methods.事实上,属性就像一个字段一样被访问,但底层的代码是方法。 The field part of a property allows you to access a value just like a field would do, though allowing you to trick this getter function and setter procedure, if I may say.属性的字段部分允许您像访问字段一样访问值,但允许您欺骗这个 getter 函数和 setter 过程,如果我可以说的话。 Properties are most commonly used to control over a field value that is assigned or returned.属性最常用于控制分配或返回的字段值。 And under the risk to repeat myself, they are accessed as a field.在重复我自己的风险下,它们作为一个领域被访问。

On the other side, functions, procedures, both known as methods in OOP, are by definition routines to process the information.另一方面,函数、过程(在 OOP 中都称为方法)根据定义是处理信息的例程。 There need to be a process over an object or piece of information, for example, it is not rare to encounter a function's name like DoThis , DoThat ... They can be used over fields or properties, but functions are known to impact more than just a field, or control a value over a field.需要对一个对象或一条信息进行处理,例如,遇到像DoThisDoThat这样的函数名称并不罕见……它们可以用于字段或属性,但众所周知,函数的影响不仅仅是只是一个字段,或者控制一个字段的值。 Functions, by opposition to properties, can have multiple parameters, optional parameters, and even be generics!与属性相反,函数可以有多个参数、可选参数,甚至可以是泛型!

I would like to add that, to my knowledge, a property cannot be anonymous, neither generic.我想补充一点,据我所知,属性不能是匿名的,也不能是通用的。 Attention, I do not say that a property cannot return a generic, I say that the property itself cannot be generic.注意,我不是说属性不能返回泛型,而是说属性本身不能是泛型。 A function can be both anonymous , and generic .一个函数既可以是anonymous ,也可以是generic

In short, a property is a concept used over a field, to gain control over a field value, while functions are doers, we expect them to perform tasks, and not just assignments.简而言之,属性是一个用于字段的概念,用于控制字段值,而函数是执行者,我们希望它们执行任务,而不仅仅是赋值。

是的,属性只是 Set/Get 方法的高级概念。

A property is the same as a function.属性与函数相同。 But a property indicates that you are getting (or setting) "properties"(Member Variables) of an object and that these getter/setter are not time consuming function that fe calculates something or queries the database.但是一个属性表明您正在获取(或设置)一个对象的“属性”(成员变量),并且这些 getter/setter不是计算某些东西或查询数据库的耗时函数。 Therefor they are a useful syntactical sugar (if they're implemented correctly).因此,它们是一种有用的语法糖(如果它们被正确实现)。

get properties are expected to be pure, and if you look into the .net Code Contracts, you'll see they assume getters are pure. get 属性应该是纯的,如果您查看 .net 代码契约,您会发现它们假定 getter 是纯的。 Thus, calling a property get once, twice or 10 times shouldnt have any difference to the object, where as calling a method on an object, may lead to multiple changes to the objects state.因此,调用属性 get 一次、两次或 10 次对对象应该没有任何区别,而在对象上调用方法可能会导致对象状态发生多次变化。

Property get/set is syntatcit sugar.属性获取/设置是语法糖。 Readonly in VB is just a way of specifying that you only want the get 'function' VB 中的只读只是一种指定您只想要获取“函数”的方法

it can then look like you should pass properties by reference (ByRef) to methods but as you point out it is a function not an actual type.然后看起来您应该通过引用(ByRef)将属性传递给方法,但正如您指出的那样,它是一个函数而不是实际类型。

I do tend to use functions for getters when the operation is expensive, eg GetCustomersFromDatabase()当操作很昂贵时,我确实倾向于使用 getter 函数,例如 GetCustomersFromDatabase()

I'd like to add, as a con for using properties, that serialization understands the concept of properties and uses them while it does not know anything about getter/setter methods.我想补充一点,作为使用属性的骗局,序列化理解属性的概念并使用它们,而它对 getter/setter 方法一无所知。 Plus, if you are using a property in a compact style like:另外,如果您使用的是紧凑样式的属性,例如:

public int MyProperty { get; private set; }

you can spare quite a lot of lines of code from your source files, making them more readable.您可以从源文件中节省相当多的代码行,使它们更具可读性。

the keyword readonly just means "Dear compiler don't expect a setter" "and if i do so, punish me".关键字 readonly 只是意味着“亲爱的编译器不要期待一个 setter”“如果我这样做了,惩罚我”。 This is a decision of VB syntax.这是VB语法的决定。 Behind the scenes functions and property getters are the same.幕后函数和属性 getter 是相同的。

The normal debug watch window for a class will show the values of non-indexed properties, but will not show the results of functions.类的正常调试观察窗口将显示非索引属性的值,但不会显示函数的结果。 One of my pet peeves with the StringBuilder class is that it does not have a property for the current string content, which makes the watch window much less useful than it would otherwise be.我对 StringBuilder 类的不满之一是它没有当前字符串内容的属性,这使得监视窗口的用处比其他情况要少得多。

Also, non-indexed properties, unlike methods, do not require a () after the name;此外,与方法不同,非索引属性不需要在名称后使用 (); I believe indexed properties in C# are required to use [] rather than () for their parameters.我相信 C# 中的索引属性需要使用 [] 而不是 () 作为其参数。

I just realized that you can send parameters in a property exact same way you do it with methods.我刚刚意识到您可以通过与使用方法完全相同的方式在属性中发送参数。 This implies you can write something like:这意味着您可以编写如下内容:

Private _ClientName As String

Public WriteOnly Property ClientName(isValid As Boolean) As String
    Set(value As String)
        If isValid Then
            _ClientName = value
        End If
    End Set
End Property

And then you can write this:然后你可以这样写:

ClientName(debt = 0) = "Richard"

Or here is another idea to validate the text set to any label control:或者这是验证文本集到任何标签控件的另一个想法:

Public WriteOnly Property OnlyNumbers(label As Label) As String
    Set(value As String)
        If Double.TryParse(value, New Double) Then
            label.Text = value
        End If
    End Set
End Property

Then you can use it like this:然后你可以像这样使用它:

OnlyNumbers(lblTotal) = debt

What I am not sure is if this is considered a "good practice" or at least a "correct" use of a property.我不确定这是否被认为是“良好做法”或至少是对财产的“正确”使用。

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

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