Joe*_*l B 46 c# reflection propertyinfo
那里有大量的反思例子可以让你得到:
1.班级中的所有属性
2.单个属性,前提是您知道字符串名称
有没有办法(使用反射,TypeDescriptor或其他方法)在运行时获取类中属性的字符串名称,前提是我拥有的是类和属性的实例?
编辑 我知道我可以使用反射轻松获取类中的所有属性,然后获取每个属性的名称.我要求的是一个函数来给我一个属性的名称,前提是我传递了属性的实例.换句话说,如何从class.GetType().GetProperty(myProperty)中找到PropertyInfo []数组返回给我的属性,以便从中获取PropertyInfo.Name?
Jac*_*cob 90
如果你已经有了PropertyInfo,那么@ dtb的回答是正确的.但是,如果您想要找出当前所在的属性代码,则必须遍历当前的调用堆栈以找出当前正在执行的方法,并从那里派生属性名称.
var stackTrace = new StackTrace();
var frames = stackTrace.GetFrames();
var thisFrame = frames[0];
var method = thisFrame.GetMethod();
var methodName = method.Name; // Should be get_* or set_*
var propertyName = method.Name.Substring(4);
Run Code Online (Sandbox Code Playgroud)
编辑:
在您澄清之后,我想知道您想要做的是从属性表达式获取属性的名称.如果是这样,您可能想要编写如下方法:
public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
Run Code Online (Sandbox Code Playgroud)
要使用它,你会写这样的东西:
var propertyName = GetPropertyName(
() => myObject.AProperty); // returns "AProperty"
Run Code Online (Sandbox Code Playgroud)
sal*_*uce 47
使用C#6.0(Visual Studio 2015),您现在可以使用nameof运算符,如下所示:
var obj = new MyObject();
string propertyName = nameof(obj.Property);
string methodName = nameof(obj.Method);
string directPropertyName = nameof(MyObject.Property);
string directMethodName = nameof(MyObject.Method);
Run Code Online (Sandbox Code Playgroud)
如果有人需要它...这里是答案的VB .NET版本:
Public Shared Function GetPropertyName(Of t)(ByVal PropertyExp As Expression(Of Func(Of t))) As String
Return TryCast(PropertyExp.Body, MemberExpression).Member.Name
End Function
Run Code Online (Sandbox Code Playgroud)
用法:
Dim name As String = GetPropertyName(Function() (New myObject).AProperty)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57011 次 |
| 最近记录: |