【问题标题】:Get the attributes from the interface methods and the class methods从接口方法和类方法中获取属性
【发布时间】:2011-09-16 20:26:04
【问题描述】:

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

例如,我想知道在下面的示例中,具有一个参数的 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;
    }
}

【问题讨论】:

    标签: c# reflection custom-attributes


    【解决方案1】:

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

    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;
    }
    

    你可以将它应用到同样容易的方法中。


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

    【讨论】:

      【解决方案2】:

      您可以使用TypeDescriptor API

      System.ComponentModel.TypeDescriptor.GetAttributes(object)
      

      【讨论】:

      • 这不是说我必须先实例化这个类吗?这会提供对象属性而不是对象方法属性吗?
      【解决方案3】:

      您应该使用反射来获取自定义属性值

      使用 MemberInfo.GetCustomAttributes Method 返回附加到您的成员的自定义属性

      这里有教程http://msdn.microsoft.com/en-us/library/aa288454(v=VS.71).aspx

      编辑:要从界面获取属性,请查看here

      【讨论】:

      • 这里还不够。使用此方法,您可以从示例中获取ScopeAttribute。对于已实现的接口和SizeAttribute,这还不够。
      猜你喜欢
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 2017-11-02
      • 2019-12-08
      • 2013-07-08
      相关资源
      最近更新 更多