将成员对象公开为 .NET 中的属性或方法

发布于 2024-07-05 21:30:27 字数 51 浏览 7 评论 0原文

在 .NET 中,如果一个类包含一个类对象成员,那么该成员应该作为属性还是通过方法公开?

In .NET, if a class contains a member that is a class object, should that member be exposed as a property or with a method?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

谁把谁当真 2024-07-12 21:30:27

您应该对概念上表示对象状态的任何内容使用属性,只要其检索不是一个昂贵的操作,您应该避免重复使用它。

来自 MSDN

类库设计者通常必须决定是将类成员实现为属性还是方法。 一般来说,方法代表动作,属性代表数据。 使用以下指南来帮助您在这些选项之间进行选择。

  • 当成员是逻辑数据成员时使用属性。 在下面的成员声明中,Name 是一个属性,因为它是类的逻辑成员。

    公共字符串名称 
      得到  
      { 
          返回名称; 
      } 
      放  
      { 
          名称=值; 
      } 
      
  • 在以下情况下使用方法:

    • 该操作是一个转换,例如 Object.ToString。
    • 该操作的成本非常高,您希望告知用户他们应该考虑缓存结果。
    • 使用 get 访问器获取属性值会产生明显的副作用。
    • 连续调用该成员两次会产生不同的结果。
    • 执行顺序很重要。 请注意,类型的属性应该能够以任何顺序设置和检索。
    • 该成员是静态的,但返回一个可以更改的值。
    • 该成员返回一个数组。 返回数组的属性可能非常具有误导性。 通常需要返回内部数组的副本,以便用户无法更改内部状态。 再加上用户可以轻松假设它是索引属性这一事实,会导致代码效率低下。 在下面的代码示例中,对Methods 属性的每次调用都会创建数组的副本。 结果,将在下面的循环中创建该数组的 2n+1 个副本。

      Type type = // 获取类型。 
        for (int i = 0; i < type.Methods.Length; i++) 
        { 
           if (type.Methods[i].Name.Equals("text")) 
           { 
              // 执行一些操作。 
           } 
        } 
        

以下示例说明了属性和方法的正确使用。

 类连接 
      { 
         // 以下三个成员应该是属性 
         // 因为它们可以按任何顺序设置。 
         字符串 DNSName {get{};set{};} 
         字符串用户名 {get{};set{};} 
         字符串密码 {get{};set{};} 

         // 下面的成员应该是一个方法 
         // 因为执行顺序很重要。 
         // 该方法必须在之后才能执行  
         // 属性已设置。 
         布尔执行(); 
      } 
  

You should use properties for anything that conceptually represents the object's state, so long as its retrieval isn't an expensive enough operation that you should avoid using it repeatedly.

From MSDN:

Class library designers often must decide between implementing a class member as a property or a method. In general, methods represent actions and properties represent data. Use the following guidelines to help you choose between these options.

  • Use a property when the member is a logical data member. In the following member declarations, Name is a property because it is a logical member of the class.

    public string Name
    get 
    {
        return name;
    }
    set 
    {
        name = value;
    }
    
  • Use a method when:

    • The operation is a conversion, such as Object.ToString.
    • The operation is expensive enough that you want to communicate to the user that they should consider caching the result.
    • Obtaining a property value using the get accessor would have an observable side effect.
    • Calling the member twice in succession produces different results.
    • The order of execution is important. Note that a type's properties should be able to be set and retrieved in any order.
    • The member is static but returns a value that can be changed.
    • The member returns an array. Properties that return arrays can be very misleading. Usually it is necessary to return a copy of the internal array so that the user cannot change internal state. This, coupled with the fact that a user can easily assume it is an indexed property, leads to inefficient code. In the following code example, each call to the Methods property creates a copy of the array. As a result, 2n+1 copies of the array will be created in the following loop.

      Type type = // Get a type.
      for (int i = 0; i < type.Methods.Length; i++)
      {
         if (type.Methods[i].Name.Equals ("text"))
         {
            // Perform some operation.
         }
      }
      

The following example illustrates the correct use of properties and methods.

    class Connection
    {
       // The following three members should be properties
       // because they can be set in any order.
       string DNSName {get{};set{};}
       string UserName {get{};set{};}
       string Password {get{};set{};}

       // The following member should be a method
       // because the order of execution is important.
       // This method cannot be executed until after the 
       // properties have been set.
       bool Execute ();
    }
凝望流年 2024-07-12 21:30:27

财产。 属性基本上只是一种“廉价”方法。 获取或设置对象的引用非常便宜。

澄清一下,属性通常应该代表对象的内部状态。 然而,将成员实现为属性或方法会告诉用户调用的成本可能有多大。

Property. A Property is basically just a 'cheap' method. Getting or setting a reference to an object is pretty cheap.

Just to clarify, properties are usually supposed to represent the internal state of an object. However, the implementation of a member as a property or method tells the user how expensive the call is likely to be.

两个我 2024-07-12 21:30:27

这与本案无关。

如果值是有关对象状态的一些详细信息,那么它应该是一个属性。

如果它对对象执行某些操作,则它应该是方法。

That is irrelevant to the matter.

It should be a Property if the value is some detail about the state of the object.

It should be Method if it performs some action on the object.

狼亦尘 2024-07-12 21:30:27

如果您所做的只是公开与当前对象状态相关的对象实例,则应该使用属性。

当您的逻辑不只是访问内存中的对象并返回该值,或者您正在执行对当前对象的状态有广泛影响的操作时,应该使用方法。

If all you are doing is exposing an object instance that is relevant to the state of the current object you should use a property.

A method should be used when you have some logic that is doing more than accessing an in memory object and returning that value or when you are performing an action that has a broad affect on the state of the current object.

梦在深巷 2024-07-12 21:30:27

概述

一般来说,属性存储对象的数据,例如名称,方法是可以要求对象执行的操作,例如移动显示。 有时,哪些类成员应该是属性、哪些应该是方法并不明显 - 集合类 (VB) 的 Item 方法存储和检索数据,并且可以作为索引属性来实现。 另一方面,将 Item 实现为方法也是合理的。

语法

类成员的使用方式也可能是决定它应该表示为属性还是方法的决定因素。 从参数化属性检索信息的语法几乎与作为函数实现的方法所使用的语法相同。 但是,修改此类值的语法略有不同。

如果将类成员实现为属性,则必须按以下方式修改其值:

ThisObject.ThisProperty(Index) = NewValue

如果类成员实现为方法,则修改的值必须使用争论进行修改:

ThisObject.ThisProperty(Index, NewValue)

错误

尝试将值分配给只读属性将返回与类似的错误消息不同的错误消息调用一个方法。 正确实现的类成员会返回更容易解释的错误消息。

Overview

Generally, properties store data for an object, such as Name, and methods are actions an object can be asked to perform, such as Move or Show. Sometimes it is not obvious which class members should be properties and which should be methods - the Item method of a collection class (VB) stores and retrieves data and can be implemented as an indexed property. On the other hand, it would also be reasonable to implement Item as a method.

Syntax

How a class member is going to be used could also be a determining factor in whether it should be represented as a property or a method. The syntax for retrieving information from a parameterized property is almost identical to the syntax used for a method implemented as a function. However, the syntax for modifying such a value is slightly different.

If you implement the member of a class as a property, you must modify it's value this way:

ThisObject.ThisProperty(Index) = NewValue

if the class member is implemented as a method, the value being modified must be modified using an arguement:

ThisObject.ThisProperty(Index, NewValue)

Errors

An attempt to assign a value to a read-only property will return a different error message than a similar call to a method. Correctly implemented class members return error messages that are easier to interpret.

稀香 2024-07-12 21:30:27

属性读取类中的实例并将值分配给该实例。

方法对分配给类的数据执行某些操作。

Properties read and assign values to instances within a class.

Methods do something with the data assigned to the class.

浪漫之都 2024-07-12 21:30:27

我之前对使用属性和方法感到困惑。 但现在我根据 使用此规则MSDN指南

方法代表动作,属性代表数据。 属性应该像字段一样使用,这意味着属性不应在计算上复杂或产生副作用。 当它不违反以下准则时,请考虑使用属性而不是方法,因为经验不足的开发人员发现属性更容易使用。

I confused about the using property and method before. But now I am using this rule according to MSDN Guideline:

methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. When it does not violate the following guidelines, consider using a property, rather than a method, because less experienced developers find properties easier to use.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文