Alp*_*age 1 c# portable-class-library
我需要获取动态调用作为参数的静态属性的属性名称.这是我的可移植类库代码:
public partial class Test
{
public Test()
{
string staticPropName = Test.GetPropName(Test.Row); // result must be "Row" without additional string
System.Diagnostics.Debug.WriteLine("propName=" + staticPropName);
}
public static int Row { get; set; }
public static string GetPropName(object Property)
{
return "Row"; // using reflection
}
}
Run Code Online (Sandbox Code Playgroud)
我不知道属性的名称,我不想用额外的字符串来定义它.
你不能这样做 - 当调用函数时,它获取属性的值,并且不知道这个值来自何处.你的样本相当于
string staticPropName = Test.GetPropName(42);
Run Code Online (Sandbox Code Playgroud)
没有人会期望返回名字.
您可以尝试将Expression参数作为参数,以便您可以实际检查调用哪个方法,如下面的凝视点(/sf/ask/70777661/财产):
public static string GetPropName<TResult>(Expression<Func<TResult>> expression)
{
MemberExpression body = (MemberExpression)expression.Body;
return body.Member.Name;
}
string staticPropName = Test.GetPropName(()=> Test.Prop);
Run Code Online (Sandbox Code Playgroud)
请注意,您需要检查以确保表达式只是您期望的表达式而不是() => Test + 42更复杂的表达式并报告错误.