从接口方法和类方法中获取属性

Phi*_*son 10 c# reflection custom-attributes

什么是在方法重载时从类方法和接口方法获取属性值的最佳方法?

例如,我想知道在下面的示例中,带有一个参数的Get方法具有两个属性,值为5和"any",而另一个方法具有值为7和"private"的属性.

public class ScopeAttribute : System.Attribute
{
    public string Allowed { get; set; }    
}

public class SizeAttribute : System.Attribute
{
    public int Max { get; set; }
}

public interface Interface1
{
    [SizeAttribute( Max = 5 )]
    string Get( string name );

    [SizeAttribute( Max = 7 )]
    string Get( string name, string area );

}

public class Class1 : Interface1
{
    [ScopeAttribute( Allowed = "any" )]
    public string Get( string name )
    {
        return string.Empty;
    }

    [ScopeAttribute( Allowed = "private" )]
    public string Get( string name, string area )
    {
        return string.Empty;
    }
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*ski 5

我发现的唯一方法是检查类实现了哪些接口并检查这些接口上的属性(如果存在)的属性:

static bool HasAttribute (PropertyInfo property, string attribute) {
  if (property == null)
    return false;

  if (GetCustomAttributes ().Any (a => a.GetType ().Name == attribute))
    return true;

  var interfaces = property.DeclaringType.GetInterfaces ();

  for (int i = 0; i < interfaces.Length; i++)
    if (HasAttribute (interfaces[i].GetProperty (property.Name), attribute))
      return true;

  return false;
}
Run Code Online (Sandbox Code Playgroud)

您可能可以将它用于同样容易的方法。


注意:整体方法已经过测试,但代码本身是临时的,可能无法编译。


Pey*_*man 1

您可以使用TypeDescriptor API

System.ComponentModel.TypeDescriptor.GetAttributes(object)
Run Code Online (Sandbox Code Playgroud)

  • 这是否意味着我必须先实例化该类?这会提供对象属性而不是对象方法属性吗? (3认同)