Simplest C# code to poll a property?

后端 未结 8 1914
慢半拍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:08

    I like Jon Skeet's answer, but along the same vein, this would also work without having to write an extension method:

    GC.KeepAlive(instance.SomeProperty);
    

    The KeepAlive method accepts an object and does nothing with it, like the NoOp extension method.

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

    Even though it's probably still a bad idea, I just want to leave this concise lambda solution:

    ((Func< [TYPE_OF_PROPERTY] >)(() => instance.Property))();
    
    0 讨论(0)
  • 2021-01-03 07:20

    (I'm assuming you're trying to avoid the warning you get from simply assigning the value to an unused variable.)

    You could write a no-op extension method:

    public static void NoOp<T>(this T value)
    {
        // Do nothing.
    }
    

    Then call:

    instance.SomeProperty.NoOp();
    

    That won't box the value or touch it at all - just call the getter. Another advantage of this over ToString is that this won't go bang if the value is a null reference.

    It will require JIT compilation of the method once per value type, but that's a pretty small cost...

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

    That sounds to me like a really terrible idea. Honestly, if you have logic in a getter that needs to be executed regularly, take it out of the getter and stick it in a method. I would hate to jump in and maintain code like that, and once I finally figured out why it was doing what it does I would refactor it.

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

    I think that you need to move the code to some where else. So try setting the global var in the constructor of your 'instance' object.

    OR.. (not sure what you mean by global variable) but if it is in a object, then you could just get the getter of the property on you global object to do a lazy load and get the value then.

    string _myProp;
    public string MyProp
    { 
       get
       {
         if (String.IsNullOrWhiteSpace(_myProp))
         {
            _myProp =  GetTheValueFromWhereEver();
         }
         return _myProp;
       }
    }
    

    (but you probably dont have access to the 'instance' there)

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

    I would extract the code in the getter to a function and call the function both, from the getter and from your poller, if this is an option for you.

    0 讨论(0)
提交回复
热议问题