Get string representation of property in C # at run time

I have seen the flip side of this question quite a few times, but have not seen how to do what I would like.

Suppose I have the following code:

var myNewData = from t in someOtherData select new { fieldName = t.Whatever, fieldName2 = t.SomeOtherWhatever }; 

If I want to bind data to this class, gated rows such as "fieldName" and "fieldName2" should be specified in my column definition.

Is there a way to cause reflection or something else so that I can do something equal to the code below (I know that the code below is not valid, but I'm looking for the right solution).

 string columnName = GetPropertyName(myNewData[0].fieldName); 

My goal is that if the variable name is changed in an anonymous class, a compile-time error will occur until all the links have been fixed, unlike the current data binding, which depends on strings that are not checked before runtime.

Any help would be appreciated.

+4
source share
2 answers
 string columnName = GetPropertyName(() => myNewData[0].fieldName); // ... public static string GetPropertyName<T>(Expression<Func<T>> expr) { // error checking etc removed for brevity MemberExpression body = (MemberExpression)expr.Body; return body.Member.Name; } 
+7
source

You get the names of your properties as follows:

 using System.Reflection; var myNewData = from t in someOtherData select new { fieldName = t.Whatever, fieldName2 = t.SomeOtherWhatever }; foreach (PropertyInfo pinfo in myNewData.FirstOrDefault() .GetType().GetProperties()) { string name = pinfo.Name; } // or if you need all strings in a list just use: List<string> propertyNames = myNewData.FirstOrDefault() .GetType().GetProperties().Select(x => x.Name).ToList(); 
+2
source

Source: https://habr.com/ru/post/1307466/


All Articles