C# 获取自定义属性目标的成员信息

标签 c# reflection

给定一个自定义属性,我想获取其目标的名称:

public class Example
{
    [Woop] ////// basically I want to get "Size" datamember name from the attribute
    public float Size;
}

public class Tester
{
    public static void Main()
    {
        Type type = typeof(Example);
        object[] attributes = type.GetCustomAttributes(typeof(WoopAttribute), false);

        foreach (var attribute in attributes)
        {
            // I have the attribute, but what is the name of it's target? (Example.Size)
            attribute.GetTargetName(); //??
        }
    }
}

希望一切都清楚!

最佳答案

反过来做:

迭代

 MemberInfo[] members = type.GetMembers();

和请求

 Object[] myAttributes = members[i].GetCustomAttributes(true);

 foreach(MemberInfo member in type.GetMembers()) {
     Object[] myAttributes = member.GetCustomAttributes(typeof(WoopAttribute),true);
     if(myAttributes.Length > 0)
     {
        MemberInfo woopmember = member; //<--- gotcha
     }
 }

但使用 Linq 会更好:

var members = from member in type.GetMembers()
    from attribute in member.GetCustomAttributes(typeof(WoopAttribute),true)
    select member;

关于C# 获取自定义属性目标的成员信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4833734/

相关文章:

java - 一个事务中的多个聚合实例

c# - JSON.Net DeserializeObject 文本编码

c# - 我可以将类型对象传递给泛型方法吗?

c# - 如何使用反射获取特定接口(interface)类型的所有字段

C# LINQ - 将类的所有属性与同一类的不同实例进行比较的 Select 语句?

C# 动态表单(反射)-链接控件

c# - 如何使用 Linq 获取唯一的实体集?

c# - 如何在单元测试中使用 Moq 和 DbFunctions 来防止 NotSupportedException?

c# - 使用上下文或创建方法在 Controller 中获取数据?

c# - 为什么反射(reflection)时内部类不公开?