Simplest C# code to poll a property?
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开发者_如何学C 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();
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...
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.
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.
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;
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);
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.
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)
Even though it's probably still a bad idea, I just want to leave this concise lambda solution:
((Func< [TYPE_OF_PROPERTY] >)(() => instance.Property))();
精彩评论