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

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

最佳答案

我发现的唯一方法是检查类实现了哪些接口(interface)并检查那些接口(interface)上的属性的属性(如果存在),例如(注意-总体方法已经过测试,但是代码本身是临时的,可能无法编译:)

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

您可能可以将其采用同样简单的方法。

关于c# - 从接口(interface)方法和类方法获取属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6380462/

10-14 20:23
查看更多