如何将属性名称作为字符串?
例如:
Public int PropertyValue{get;set;}
现在我希望将PropertyValue作为一个带有反射的字符串,并使用foreach PropertyInfo
答案 0 :(得分:1)
我在这里找到了一个解决方案: Workaround for lack of 'nameof' operator in C# for type-safe databinding?
@reshefm有这段代码的地方:
class Program
{
static void Main()
{
var propName = Nameof<SampleClass>.Property(e => e.Name);
Console.WriteLine(propName);
}
}
public class Nameof<T>
{
public static string Property<TProp>(Expression<Func<T, TProp>> expression)
{
var body = expression.Body as MemberExpression;
if(body == null)
throw new ArgumentException("'expression' should be a member expression");
return body.Member.Name;
}
}
希望这会有所帮助:)