简体   繁体   中英

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 great, 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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM