C# 如何从属性中获取值?

C# 如何从属性中获取值?,c#,attributes,C#,Attributes,让我们在ctor中有一个具有int参数的属性 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] public class EntityBindingAttribute : Attribute { public int I { get; set; } public EntityBindingAttribute(int i) { I = i; } } 如何使用代

让我们在ctor中有一个具有int参数的属性

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]
public class EntityBindingAttribute : Attribute
{
    public int I { get; set; }

    public EntityBindingAttribute(int i)
    {
        I = i;
    }
}
如何使用代码访问此值?

您可以使用,重载与设置属性的对象相匹配

例如,如果在方法上设置了属性,则类似于:

MethodInfo mInfo = myClass.GetMethod("MyMethod");
foreach(Attribute attr in Attribute.GetCustomAttributes(mInfo))
{
   if (attr.GetType() == typeof(EntityBindingAttribute))
   {
     int i = ((EntityBindingAttribute)attr).I);
    }
}
您将使用与设置属性的对象匹配的重载

例如,如果在方法上设置了属性,则类似于:

MethodInfo mInfo = myClass.GetMethod("MyMethod");
foreach(Attribute attr in Attribute.GetCustomAttributes(mInfo))
{
   if (attr.GetType() == typeof(EntityBindingAttribute))
   {
     int i = ((EntityBindingAttribute)attr).I);
    }
}

哪个方法用于从类中获取属性?System.Type实际上是System.Reflection.MemberInfo,所以它是相同的方法,就像这个Attribute.GetCustomAttributes(typeof(MyClass))哪个方法用于从类中获取属性?System.Type实际上是System.Reflection.MemberInfo,所以它是相同的方法,与此属性类似。GetCustomAttributes(typeof(MyClass))只要属性类具有该属性,它就可以工作。是的,在注释“假设有一个”中提到。在访问属性I之前,很容易将代码更改为使用FirstOrDefault,然后检查空引用。为了清楚起见,在回答中省略了这一点。只要属性类具有该属性,这种方法就有效。是的,在注释“假设有一个”中提到。很容易将代码更改为使用FirstOrDefault,然后在访问属性I之前检查空引用。为了清楚起见,在回答中省略了这一点。