开发者

C# Get the name of a non-static property of a class

I have a question very similiar to another question: Get name of property as a string.

His solution ended up with

// Static Property 
string name = GetPropertyName(() => SomeClass.SomeProperty); 

// Instance Property 
string name = GetPropertyName(() => someObject.SomeProperty); 

What I'd like is to have syntax similar to the Static Property but for an instance property.

The reason is that I have code now that uses reflection to get the value of a property for all objects within a collection, but i have to pass that in as a hardcoded string.

Example code:

double Sum = AmountCollection.Sum("thatfield");  

Well, this works gre开发者_如何学Cat, but if "thatfield" was ever renamed, the code would no longer work. The compiler cant check for that since it's just a string. Also, Get References won't work either for the same reason.

So, is there a way to achieve the goal of getting a property name easily, (ie; just a function call), from an instance property?

Thanks.


Try this:

string name = GetPropertyName(() => default(SomeClass).SomeInstanceProperty);

You may get a compiler warning about "always causing a System.NullReferenceException", but that's not actually happening, since you don't execute the expression, which means that you can safely discard this warning. If you want to get rid of it, either disable it via pragma or just move the default() call into a function like this:

public static T Dummy<T>() {
  return default(T);
}

string name = GetPropertyName(() => Dummy<SomeClass>().SomeInstanceProperty);


With C# 6.0 you use nameof :

 nameof(SomeProperty)

This expression is resolved at compile-time to "SomeProperty".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜