问题描述
我想知道投票最简单的代码属性值,在其吸气剂来执行代码结果
目前我使用: instance.property.ToString( );
,但我宁愿有没有可能产生的副作用或不必要的开销东西
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();
, but I'd rather have something without possible side-effects or unnecessary overhead.
推荐答案
(我假设你正在试图避免你从简单的值赋给一个未使用的变量得到警告。)
(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();
这不会框中的值或触摸它在所有 - 只需调用吸气。在的ToString
这样做的另一个好处是,如果该值是一个空引用这不会爆炸。
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.
它的将会的要求每个值类型一旦方法的JIT编译,但是这是一个非常小的费用...
It will require JIT compilation of the method once per value type, but that's a pretty small cost...
这篇关于最简单的C#代码轮询的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!