Simplest C# code to poll a property?

后端 未结 8 1915
慢半拍i
慢半拍i 2021-01-03 06:31

I would like to know the simplest code for polling a property\'s value, to execute the code in its getter.
Currently I\'m using: instance.property.ToString();

相关标签:
8条回答
  • 2021-01-03 07:32

    Capturing it in a variable is the best way - doesn't cause any side-effects unless the getter itself causes side-effects.

    var value = someObj.Property;

    0 讨论(0)
  • 2021-01-03 07:33

    I hope i understand that correct. First of all

    class MyClass
    {
       public int Number{get;set;}
    }
    
    var cl = new MyClass();
    cl.Number.ToString();
    

    The ToString() does not necessarily return the value, for primitives this is the case, yes, but for other more complex classes it is usually only the full qualified name. And i guess this is not what you want.

    To execute the getter, you need some reflection.

    var propInfo = this.GetType().GetProperty("Number");
    int val = (int)propInfo.GetValue(cl, null);
    
    0 讨论(0)
提交回复
热议问题