Simplest C# code to poll a property?

后端 未结 8 1950
慢半拍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: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(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...

提交回复
热议问题