1

我有一个简单的问题。我设计了一个 C# 类,在那里我得到了一些属性获取器,他们负责执行一些性能昂贵的任务。我班上有很多这样的属性。我的问题是,一旦将类的实例加载到内存中,这些属性获取器是否会被评估?如果是这样,那么,我会考虑将它们分解为方法。我希望他们只在第一次使用该属性时进行评估,但我需要确定这个假设。

我知道我应该为昂贵的任务使用方法,但我刚刚发现使用属性更易于维护,因为我在一个类中有很多成员。

谢谢。

4

5 回答 5

6

每次调用/调用它们时都会评估属性 getter/setter。它们只不过是方法的语法。

public class Foo
{
   private int actual = 0;
   public int Bar
   {
      get { return actual++; }
      set { value = actual; value++ }
   }
}

int v = foo.Bar; //0
v = foo.Bar; // 1
v = foo.Bar; // 2
foo.Bar = v; // actual = 3
于 2012-05-09T00:29:42.707 回答
3

Property getters are not for instantiation, since getters/setters only run when you call the property. Use the constructor for instantiating properties. The exception to this rule is lazy initialization, when a (usually readonly) property's value is initialized the first time it is accessed.

于 2012-05-09T00:33:30.447 回答
3

No, they will not be evaluated when the class is instantiated. They will only be evaluated when they are accessed (and every time thereafter). This allows you to implementat "lazy-loading". It may be wise (depending on your situation) to save the result in a private field after evaluating once, and returning that result for every subsequent call.

private string foo;
public string Foo
{
  get
  { 
    if (foo == null)
      foo = "expensive operation";
    return foo;
  }
}
于 2012-05-09T00:33:32.973 回答
1

Getters/setters are evaluated when you do call them. Consider this:

    private string sample;
    public  string Sample
    {
        get
        {
            return (sample = sample ?? SomeExpensiveMethod());
        }
    }

This way you can control when to call your expensive method.

Also consider static properties are populated only once in your application lifetime. So that can also be a choice, depending on your scenario.

于 2012-05-09T00:34:27.787 回答
0

值得一提的是,您还可以使用关键字“value”来评估要分配的值。例如:

public String Author
    {
        get { return author; } 
        set 
        {
            if (value.Equals(""))
                Console.WriteLine();
            else
                author = value; 
        }
    }

这样,您可以评估分配。

于 2017-03-28T11:37:37.723 回答