我想通过反射机制获取属性名。有可能吗?
更新:我有这样的代码:
public CarType Car
{
get { return (Wheel) this["Wheel"];}
set { this["Wheel"] = value; }
}因为我需要更多这样的属性,所以我想这样做:
public CarType Car
{
get { return (Wheel) this[GetThisPropertyName()];}
set { this[GetThisPropertyName()] = value; }
}发布于 2009-07-30 11:40:21
改用MethodBase.GetCurrentMethod()!
反射用于处理在编译时无法完成的类型。获取您所在的属性访问器的名称可以在编译时决定,因此您可能不应该使用反射。
不过,您可以使用System.Diagnostics.StackTrace从调用堆栈中使用访问器方法的名称。
string GetPropertyName()
{
StackTrace callStackTrace = new StackTrace();
StackFrame propertyFrame = callStackTrace.GetFrame(1); // 1: below GetPropertyName frame
string properyAccessorName = propertyFrame.GetMethod().Name;
return properyAccessorName.Replace("get_","").Replace("set_","");
}https://stackoverflow.com/questions/1206023
复制相似问题