首先也是最重要的 - 马克,非常感谢你提供了一个很棒的图书馆!
其次,请原谅我马克,因为我即将犯罪......
我遇到了同样的问题 - 希望访问有关成员的 MemberInfo,但库让我“嗅探”它,但不能访问它。
在http://www.codeproject.com/Articles/80343/Accessing-private-members.aspx的帮助下
public static class SillyMemberExtensions
{
public static T GetPrivateField<T>(this object obj, string name)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
Type type = obj.GetType();
FieldInfo field = type.GetField(name, flags);
return (T)field.GetValue(obj);
}
public static T GetPrivateProperty<T>(this object obj, string name)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
Type type = obj.GetType();
PropertyInfo field = type.GetProperty(name, flags);
return (T)field.GetValue(obj, null);
}
public static MemberInfo GetMemberInfo(this FastMember.Member member)
{
return GetPrivateField<MemberInfo>(member, "member");
}
public static T GetMemberAttribute<T>(this FastMember.Member member) where T : Attribute
{
return GetPrivateField<MemberInfo>(member, "member").GetCustomAttribute<T>();
}
}
用法:
if (m.IsDefined(typeof(MyCustomAttribute)))
{
var attr = m.GetMemberAttribute<MyCustomAttribute>();
if (attr.SomeCustomParameterInTheAttribute >= 10)
return "More than 10";
}