如何使用FastMember获取成员的属性数据 [英] How to get the Attribute data of a Member with FastMember
问题描述
使用 NuGet 的 FastMember 库,我能够找到用特定属性修饰的类型,使用以下代码:
using the FastMember library from NuGet, I am able to find all the members of a type that are decorated with a particular attribute, using this code:
var accessor = TypeAccessor.Create(typeof (MyData));
var decoratedMembers = accessor.GetMembers().Where(x=>x.IsDefined(typeof(MyDecorationAttribute));
这一切都很好,但我现在需要能够为 decoratedMembers
MemberSet<中的每个成员获取
MyDecorationAttribute
的特定实例/code> 并且据我所知没有办法做到这一点.
That's all very well and good, but I need to now be able to get the specific instance of MyDecorationAttribute
for each of the members in decoratedMembers
MemberSet
and as far as I can see there isn't a way to do that.
我错过了什么吗?也许我应该使用不同的库来获取每个成员的属性数据,或者在这种情况下使用股票反射.
Am I missing something? Perhaps there's a different library that I should be using to get the attribute data per member, or is stock Reflection the way to go in this case.
推荐答案
首先 - Marc,非常感谢您提供了一个很棒的库!
First and foremost - Marc, thank you very much for an AWESOME library!
其次,请原谅我马克,因为我快要犯罪了...
Second, please forgive me Marc, for I am about to sin...
我遇到了同样的问题 - 希望访问关于成员的 MemberInfo,但图书馆让我嗅探"它,但不能访问它.
I have had the same problem - a desire to access a MemberInfo about the member, but library lets me "sniff" it, but not to access it.
在 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";
}
这篇关于如何使用FastMember获取成员的属性数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!