在干将对象创建不好的做法? [英] Is object creation in getters bad practice?

查看:92
本文介绍了在干将对象创建不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们在一个getter创建这样一个对象:

Let's have an object created in a getter like this :

public class Class1
{
       public string Id { get; set; }
       public string Oz { get; set; }
       public string Poznamka { get; set; }

       public Object object
       {
             get
             {
                  // maybe some more code
                  return new Object { Id = Id, poznamla = Poznamka, Oz = OZ };
             }
        }
 }



还是应该我宁愿创建方法将创建并返回对象?

Or should I rather create a Method that will create and return the object ?

推荐答案

属性看起来像场,但他们的方法。这已经知道,造成混乱的一个惊人的数量。当程序员看到,似乎是访问域代码,有很多假设,程序员做的可能不是真的为property.So有一些共同的特性设计指南。

Properties look like fields but they are methods. This has been known to cause a phenomenal amount of confusion. When a programmer sees code that appears to be accessing a field, there are many assumptions that the programmer makes that may not be true for a property.So there are some common properties design guidelines.


  1. 避免来自属性的getter返回不同的值。如果在连续多次调用,一个属性方法可以在每次返回不同的值;一个字段返回每个时间相同的值。

  1. Avoid returning different values from the property getter. If called multiple times in a row, a property method may return a different value each time; a field returns the same value each time.

一个属性方法可能需要额外的内存,或者返回一个参考的东西,实际上不是对象状态的一部分,因此修改返回的对象有没有影响原来的对象;查询一个字段始终返回到保证是原始对象的状态的一部分的对象的引用。与返回副本可以非常混乱,以开发商物业的工作,而这个特性经常没有记录。

A property method may require additional memory or return a reference to something that is not actually part of the object's state, so modifying the returned object has no effect on the original object; querying a field always returns a reference to an object that is guaranteed to be part of the original object's state. Working with a property that returns a copy can be very confusing to developers, and this characteristic is frequently not documented.

认为这是一个属性不能作为传递out或ref参数的方法;一个字段可以。

Consider that a property cannot be passed as an out or ref parameter to a method; a field can.

避免长时间运行的属性获取。一个属性方法需要很长的时间来执行;字段访问总是立即完成。

Avoid long running property getters. A property method can take a long time to execute; field access always completes immediately.

避免从干将抛出异常。

不要保留以前的值,如果属性setter抛出一个异常

Do preserve previous values if a property setter throws an exception

避免观察到的副作用。

Avoid observable side effects.

允许属性,即使这会导致对象的临时无效状态的任何命令来设置。

Allow properties to be set in any order even if this results in a temporary invalid state of objects.

来源

通过C#CLR ,杰弗里里希特。第9章定义属性智能化

"CLR via C#", Jeffrey Richter. Chapter 9. Defining Properties Intelligently

框架设计准则第二版,布拉德·艾布拉姆斯,克日什托夫·Cwalina,第5.2章地产设计

"Framework Design Guidelines" 2nd edition, Brad Abrams, Krzysztof Cwalina, Chapter 5.2 Property Design

这篇关于在干将对象创建不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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