要使用只读属性还是方法?

时间:2022-09-12 08:43:34

I need to expose the "is mapped?" state of an instance of a class. The outcome is determined by a basic check. It is not simply exposing the value of a field. I am unsure as to whether I should use a read-only property or a method.

我需要公开类实例的“is mapping ?”状态。结果由基本检查决定。它不只是公开字段的值。我不确定应该使用只读属性还是方法。

Read-only property:

只读属性:

public bool IsMapped
{
    get
    {
        return MappedField != null;
    }
}

Method:

方法:

public bool IsMapped()
{
    return MappedField != null;
}

I have read MSDN's Choosing Between Properties and Methods but I am still unsure.

我已经阅读了MSDN在属性和方法之间的选择,但是我仍然不确定。

12 个解决方案

#1


83  

The C# standard says

c#标准说

§ 8.7.4

§8.7.4

A property is a member that provides access to a characteristic of an object or a class. Examples of properties include the length of a string, the size of a font, the caption of a window, the name of a customer, and so on. Properties are a natural extension of fields. Both are named members with associated types, and the syntax for accessing fields and properties is the same. However, unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the statements to be executed when their values are read or written.

属性是提供对对象或类特性的访问的成员。属性的示例包括字符串长度、字体大小、窗口标题、客户名等。属性是字段的自然扩展。它们都是具有关联类型的命名成员,访问字段和属性的语法是相同的。但是,与字段不同,属性不表示存储位置。相反,属性具有访问器,指定在读取或写入值时执行的语句。

while as methods are defined as

而as方法定义为

§ 8.7.3

§8.7.3

A method is a member that implements a computation or action that can be performed by an object or class. Methods have a (possibly empty) list of formal parameters, a return value (unless the method’s return-type is void ), and are either static or non-static.

方法是实现可由对象或类执行的计算或操作的成员。方法有一个(可能是空的)形式参数列表、返回值(除非方法的返回类型为void),并且要么是静态的,要么是非静态的。

Properties and methods are used to realize encapsulation. Properties encapsulate data, methods encapsulate logic. And this is why you should prefer a read-only property if you are exposing data. In your case there is no logic that modifies the internal state of your object. You want to provide access to a characteristic of an object.

使用属性和方法实现封装。属性封装数据,方法封装逻辑。这就是为什么在公开数据时应该选择只读属性。在您的例子中,没有逻辑可以修改对象的内部状态。您希望提供对对象特性的访问。

Whether an instance of your object IsMapped or not is a characteristic of your object. It contains a check, but that's why you have properties to access it. Properties can be defined using logic, but they should not expose logic. Just like the example mentioned in the first quote: Imagine the String.Length property. Depending on the implementation, it may be that this property loops through the string and counts the characters. It also does perform an operation, but "from the outside" it just give's an statement over the internal state/characteristics of the object.

对象的实例是否被映射是对象的特征。它包含一个检查,但这就是为什么您有属性来访问它。属性可以使用逻辑来定义,但是它们不应该公开逻辑。就像第一句中提到的例子:想象弦。长度属性。根据实现的不同,这个属性可能在字符串中循环并计数字符。它也执行一个操作,但是“从外部”它只给出一个关于对象的内部状态/特征的语句。

#2


21  

I would use the property, because there is no real "doing" (action), no side effects and it's not too complex.

我会使用这个属性,因为没有真正的“做”(动作),没有副作用,也不太复杂。

#3


11  

I personally believe that a method should do something or perform some action. You are not performing anything inside IsMapped so it should be a property

我个人认为一个方法应该做点什么或者做点什么。您没有在ismapping中执行任何操作,因此它应该是一个属性

#4


7  

I'd go for a property. Mostly because the first senctence on the referenced MSDN-article:

我想要一个财产。主要是因为参考的msdn文章的第一个主题:

In general, methods represent actions and properties represent data.

通常,方法表示操作,属性表示数据。

#5


4  

In this case it seems pretty clear to me that it should be a property. It's a simple check, no logic, no side effects, no performance impact. It doesn't get much simpler than that check.

在这种情况下,我很清楚它应该是一个属性。这是一个简单的检查,没有逻辑,没有副作用,没有性能影响。没有比这更简单的了。

Edit:

编辑:

Please note that if there was any of the above mentioned and you would put it into a method, that method should include a strong verb, not an auxiliary verb like is or has. A method does something. You could name it VerifyMapping or DetermineMappingExistance or something else as long as it starts with a verb.

请注意,如果上面提到过任何一种方法,你可以将它放入一个方法中,这个方法应该包含一个强动词,而不是像is或has这样的助动词。一个做了一些方法。你可以给它命名为VerifyMapping或DetermineMappingExistance或者其他名称只要它是以动词开头的。

#6


4  

I think this line in your link is the answer

我认为你链接中的这条线就是答案

methods represent actions and properties represent data.

方法表示操作,属性表示数据。

There is no action here, just a piece of data. So it's a Property.

这里没有动作,只有数据。这是一个性质。

#7


3  

If at any point you'll need to add parameters in order to get the value, then you need a method. Otherwise you need a property

如果在任何时候您都需要添加参数以获取值,那么您需要一个方法。否则你需要一个属性

#8


2  

IMHO , the first read-only property is correct because IsMapped as a Attribute of your object, and you're not performing an action (only an evaluation), but at the end of the day consistancy with your existing codebase probably counts for more than semantics.... unless this is a uni assignment

恕我直言,只读属性是正确的因为IsMapped作为对象的属性,和你不执行一个动作(只有一个评估),但在一天结束的时候consistancy可能与您现有的代码库数量超过语义....除非这是单项作业

#9


2  

I'll agree with people here in saying that because it is obtaining data, and has no side-effects, it should be a property.

我同意这里的人的说法,因为它正在获取数据,而且没有副作用,所以它应该是一个属性。

To expand on that, I'd also accept some side-effects with a setter (but not a getter) if the side-effects made sense to someone "looking at it from the outside".

为了进一步说明这一点,如果副作用对“从外部观察”的人有意义的话,我也会接受setter(但不是getter)的一些副作用。

One way to think about it is that methods are verbs, and properties are adjectives (meanwhile, the objects themselves are nouns, and static objects are abstract nouns).

一种理解方法是动词,属性是形容词(同时,对象本身是名词,静态对象是抽象名词)。

The only exception to the verb/adjective guideline is that it can make sense to use a method rather than a property when obtaining (or setting) the information in question can be very expensive: Logically, such a feature should probably still be a property, but people are used to thinking of properties as low-impact performance-wise and while there's no real reason why that should always be the case, it could be useful to highlight that GetIsMapped() is relatively heavy perform-wise if it in fact was.

动词/形容词指南的唯一例外是,在获取(或设置)相关信息时,使用方法而不是使用属性是有意义的:从逻辑上讲,这样的特性应该仍然是一个属性,但人们习惯于考虑属性少属性虽然没有真正的原因应该是这种情况,它可能是有用的强调GetIsMapped()如果它事实上是perform-wise相对较大。

At the level of the running code, there's absolutely no difference between calling a property and calling an equivalent method to get or set; it's all about making life easier for the person writing code that uses it.

在运行代码的级别上,调用属性和调用等效方法来获取或设置是没有区别的;这一切都是为了让编写代码的人更轻松。

#10


2  

In situations/languages where you have access to both of these constructs, the general divide is as follows:

在可以同时使用这两种结构的情况/语言中,一般的差异如下:

  • If the request is for something the object has, use a property (or a field).
  • 如果请求是对象拥有的某样东西,请使用属性(或字段)。
  • If the request is for the result of something the object does, use a method.
  • 如果请求是对象所做事情的结果,请使用方法。

A little more specifically, a property is to be used to access, in read and/or write fashion, a data member that is (for consuming purposes) owned by the object exposing the property. Properties are better than fields because the data doesn't have to exist in persistent form all the time (they allow you to be "lazy" about calculation or retrieval of this data value), and they're better than methods for this purpose because you can still use them in code as if they were public fields.

更具体地说,属性将被用于访问公开属性的对象(用于消费目的)所拥有的数据成员(以读和/或写的方式)。属性比字段,因为数据没有持久的形式存在的(他们让你“懒惰”计算或检索的数据值),而且他们比方法为这个目的,因为你仍然可以使用它们在代码中好像他们是公共领域。

Properties should not, however, result in side effects (with the possible, understandable exception of setting a variable meant to persist the value being returned, avoiding expensive recalculation of a value needed many times); they should, all other things being equal, return a deterministic result (so NextRandomNumber is a bad conceptual choice for a property) and the calculation should not result in the alteration of any state data that would affect other calculations (for instance, getting PropertyA and PropertyB in that order should not return any different result than getting PropertyB and then PropertyA).

但是,属性不应导致副作用(可以理解的例外是,设置一个旨在持久保存要返回的值的变量,避免代价高昂的重新计算需要多次的值);他们应该,在其他条件相同的情况下,返回一个确定性的结果(所以NextRandomNumber属性)是一个糟糕的概念选择和计算不应导致任何状态数据的变更会影响其他计算(例如,越来越PropertyA PropertyB依次不应该返回任何比PropertyB然后PropertyA)不同的结果。

A method, OTOH, is conceptually understood as performing some operation and returning the result; in short, it does something, which may extend beyond the scope of computing a return value. Methods, therefore, are to be used when an operation that returns a value has additional side effects. The return value may still be the result of some calculation, but the method may have computed it non-deterministically (GetNextRandomNumber()), or the returned data is in the form of a unique instance of an object, and calling the method again produces a different instance even if it may have the same data (GetCurrentStatus()), or the method may alter state data such that doing exactly the same thing twice in a row produces different results (EncryptDataBlock(); many encryption ciphers work this way by design to ensure encrypting the same data twice in a row produces different ciphertexts).

在概念上,OTOH方法被理解为执行某些操作并返回结果;简而言之,它做了一些事情,这可能超出了计算返回值的范围。因此,当返回值的操作具有附加副作用时,将使用方法。返回值可能仍然是某些计算的结果,但计算方法可能non-deterministically(GetNextRandomNumber()),或者返回的数据的形式是独一无二的一个对象的实例,并再次调用的方法产生不同的实例,即使它可能有相同的数据(GetCurrentStatus()),或者方法可能改变状态数据,这样连续两次做同样的事情会产生不同的结果(EncryptDataBlock();许多加密密码设计成这种方式,以确保对同一数据进行两次加密,从而产生不同的密文)。

#11


1  

I would expect property as it only is returning the detail of a field. On the other hand I would expect

我期望属性,因为它只返回字段的细节。另一方面,我希望

MappedFields[] mf;
public bool IsMapped()
{
     mf.All(x => x != null);
}

#12


0  

you should use the property because c# has properties for this reason

您应该使用该属性,因为c#出于这个原因具有属性

#1


83  

The C# standard says

c#标准说

§ 8.7.4

§8.7.4

A property is a member that provides access to a characteristic of an object or a class. Examples of properties include the length of a string, the size of a font, the caption of a window, the name of a customer, and so on. Properties are a natural extension of fields. Both are named members with associated types, and the syntax for accessing fields and properties is the same. However, unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the statements to be executed when their values are read or written.

属性是提供对对象或类特性的访问的成员。属性的示例包括字符串长度、字体大小、窗口标题、客户名等。属性是字段的自然扩展。它们都是具有关联类型的命名成员,访问字段和属性的语法是相同的。但是,与字段不同,属性不表示存储位置。相反,属性具有访问器,指定在读取或写入值时执行的语句。

while as methods are defined as

而as方法定义为

§ 8.7.3

§8.7.3

A method is a member that implements a computation or action that can be performed by an object or class. Methods have a (possibly empty) list of formal parameters, a return value (unless the method’s return-type is void ), and are either static or non-static.

方法是实现可由对象或类执行的计算或操作的成员。方法有一个(可能是空的)形式参数列表、返回值(除非方法的返回类型为void),并且要么是静态的,要么是非静态的。

Properties and methods are used to realize encapsulation. Properties encapsulate data, methods encapsulate logic. And this is why you should prefer a read-only property if you are exposing data. In your case there is no logic that modifies the internal state of your object. You want to provide access to a characteristic of an object.

使用属性和方法实现封装。属性封装数据,方法封装逻辑。这就是为什么在公开数据时应该选择只读属性。在您的例子中,没有逻辑可以修改对象的内部状态。您希望提供对对象特性的访问。

Whether an instance of your object IsMapped or not is a characteristic of your object. It contains a check, but that's why you have properties to access it. Properties can be defined using logic, but they should not expose logic. Just like the example mentioned in the first quote: Imagine the String.Length property. Depending on the implementation, it may be that this property loops through the string and counts the characters. It also does perform an operation, but "from the outside" it just give's an statement over the internal state/characteristics of the object.

对象的实例是否被映射是对象的特征。它包含一个检查,但这就是为什么您有属性来访问它。属性可以使用逻辑来定义,但是它们不应该公开逻辑。就像第一句中提到的例子:想象弦。长度属性。根据实现的不同,这个属性可能在字符串中循环并计数字符。它也执行一个操作,但是“从外部”它只给出一个关于对象的内部状态/特征的语句。

#2


21  

I would use the property, because there is no real "doing" (action), no side effects and it's not too complex.

我会使用这个属性,因为没有真正的“做”(动作),没有副作用,也不太复杂。

#3


11  

I personally believe that a method should do something or perform some action. You are not performing anything inside IsMapped so it should be a property

我个人认为一个方法应该做点什么或者做点什么。您没有在ismapping中执行任何操作,因此它应该是一个属性

#4


7  

I'd go for a property. Mostly because the first senctence on the referenced MSDN-article:

我想要一个财产。主要是因为参考的msdn文章的第一个主题:

In general, methods represent actions and properties represent data.

通常,方法表示操作,属性表示数据。

#5


4  

In this case it seems pretty clear to me that it should be a property. It's a simple check, no logic, no side effects, no performance impact. It doesn't get much simpler than that check.

在这种情况下,我很清楚它应该是一个属性。这是一个简单的检查,没有逻辑,没有副作用,没有性能影响。没有比这更简单的了。

Edit:

编辑:

Please note that if there was any of the above mentioned and you would put it into a method, that method should include a strong verb, not an auxiliary verb like is or has. A method does something. You could name it VerifyMapping or DetermineMappingExistance or something else as long as it starts with a verb.

请注意,如果上面提到过任何一种方法,你可以将它放入一个方法中,这个方法应该包含一个强动词,而不是像is或has这样的助动词。一个做了一些方法。你可以给它命名为VerifyMapping或DetermineMappingExistance或者其他名称只要它是以动词开头的。

#6


4  

I think this line in your link is the answer

我认为你链接中的这条线就是答案

methods represent actions and properties represent data.

方法表示操作,属性表示数据。

There is no action here, just a piece of data. So it's a Property.

这里没有动作,只有数据。这是一个性质。

#7


3  

If at any point you'll need to add parameters in order to get the value, then you need a method. Otherwise you need a property

如果在任何时候您都需要添加参数以获取值,那么您需要一个方法。否则你需要一个属性

#8


2  

IMHO , the first read-only property is correct because IsMapped as a Attribute of your object, and you're not performing an action (only an evaluation), but at the end of the day consistancy with your existing codebase probably counts for more than semantics.... unless this is a uni assignment

恕我直言,只读属性是正确的因为IsMapped作为对象的属性,和你不执行一个动作(只有一个评估),但在一天结束的时候consistancy可能与您现有的代码库数量超过语义....除非这是单项作业

#9


2  

I'll agree with people here in saying that because it is obtaining data, and has no side-effects, it should be a property.

我同意这里的人的说法,因为它正在获取数据,而且没有副作用,所以它应该是一个属性。

To expand on that, I'd also accept some side-effects with a setter (but not a getter) if the side-effects made sense to someone "looking at it from the outside".

为了进一步说明这一点,如果副作用对“从外部观察”的人有意义的话,我也会接受setter(但不是getter)的一些副作用。

One way to think about it is that methods are verbs, and properties are adjectives (meanwhile, the objects themselves are nouns, and static objects are abstract nouns).

一种理解方法是动词,属性是形容词(同时,对象本身是名词,静态对象是抽象名词)。

The only exception to the verb/adjective guideline is that it can make sense to use a method rather than a property when obtaining (or setting) the information in question can be very expensive: Logically, such a feature should probably still be a property, but people are used to thinking of properties as low-impact performance-wise and while there's no real reason why that should always be the case, it could be useful to highlight that GetIsMapped() is relatively heavy perform-wise if it in fact was.

动词/形容词指南的唯一例外是,在获取(或设置)相关信息时,使用方法而不是使用属性是有意义的:从逻辑上讲,这样的特性应该仍然是一个属性,但人们习惯于考虑属性少属性虽然没有真正的原因应该是这种情况,它可能是有用的强调GetIsMapped()如果它事实上是perform-wise相对较大。

At the level of the running code, there's absolutely no difference between calling a property and calling an equivalent method to get or set; it's all about making life easier for the person writing code that uses it.

在运行代码的级别上,调用属性和调用等效方法来获取或设置是没有区别的;这一切都是为了让编写代码的人更轻松。

#10


2  

In situations/languages where you have access to both of these constructs, the general divide is as follows:

在可以同时使用这两种结构的情况/语言中,一般的差异如下:

  • If the request is for something the object has, use a property (or a field).
  • 如果请求是对象拥有的某样东西,请使用属性(或字段)。
  • If the request is for the result of something the object does, use a method.
  • 如果请求是对象所做事情的结果,请使用方法。

A little more specifically, a property is to be used to access, in read and/or write fashion, a data member that is (for consuming purposes) owned by the object exposing the property. Properties are better than fields because the data doesn't have to exist in persistent form all the time (they allow you to be "lazy" about calculation or retrieval of this data value), and they're better than methods for this purpose because you can still use them in code as if they were public fields.

更具体地说,属性将被用于访问公开属性的对象(用于消费目的)所拥有的数据成员(以读和/或写的方式)。属性比字段,因为数据没有持久的形式存在的(他们让你“懒惰”计算或检索的数据值),而且他们比方法为这个目的,因为你仍然可以使用它们在代码中好像他们是公共领域。

Properties should not, however, result in side effects (with the possible, understandable exception of setting a variable meant to persist the value being returned, avoiding expensive recalculation of a value needed many times); they should, all other things being equal, return a deterministic result (so NextRandomNumber is a bad conceptual choice for a property) and the calculation should not result in the alteration of any state data that would affect other calculations (for instance, getting PropertyA and PropertyB in that order should not return any different result than getting PropertyB and then PropertyA).

但是,属性不应导致副作用(可以理解的例外是,设置一个旨在持久保存要返回的值的变量,避免代价高昂的重新计算需要多次的值);他们应该,在其他条件相同的情况下,返回一个确定性的结果(所以NextRandomNumber属性)是一个糟糕的概念选择和计算不应导致任何状态数据的变更会影响其他计算(例如,越来越PropertyA PropertyB依次不应该返回任何比PropertyB然后PropertyA)不同的结果。

A method, OTOH, is conceptually understood as performing some operation and returning the result; in short, it does something, which may extend beyond the scope of computing a return value. Methods, therefore, are to be used when an operation that returns a value has additional side effects. The return value may still be the result of some calculation, but the method may have computed it non-deterministically (GetNextRandomNumber()), or the returned data is in the form of a unique instance of an object, and calling the method again produces a different instance even if it may have the same data (GetCurrentStatus()), or the method may alter state data such that doing exactly the same thing twice in a row produces different results (EncryptDataBlock(); many encryption ciphers work this way by design to ensure encrypting the same data twice in a row produces different ciphertexts).

在概念上,OTOH方法被理解为执行某些操作并返回结果;简而言之,它做了一些事情,这可能超出了计算返回值的范围。因此,当返回值的操作具有附加副作用时,将使用方法。返回值可能仍然是某些计算的结果,但计算方法可能non-deterministically(GetNextRandomNumber()),或者返回的数据的形式是独一无二的一个对象的实例,并再次调用的方法产生不同的实例,即使它可能有相同的数据(GetCurrentStatus()),或者方法可能改变状态数据,这样连续两次做同样的事情会产生不同的结果(EncryptDataBlock();许多加密密码设计成这种方式,以确保对同一数据进行两次加密,从而产生不同的密文)。

#11


1  

I would expect property as it only is returning the detail of a field. On the other hand I would expect

我期望属性,因为它只返回字段的细节。另一方面,我希望

MappedFields[] mf;
public bool IsMapped()
{
     mf.All(x => x != null);
}

#12


0  

you should use the property because c# has properties for this reason

您应该使用该属性,因为c#出于这个原因具有属性