繁体   English   中英

如何通过属性定义类型?

[英]How to define Type through Attributes?

通常,在函数类A上有一个属性Atr,我想要另一个类B,类型获取在其中注册了Atr的类。 在我的情况下,它应该仅是Type = typeof(A)而没有A。希望您能理解。 感谢您的回答。

这是示例代码。

public class Atr: Attribute
{
    public Atr()
    {
        DefaultDescription = "hello";
        Console.WriteLine("I am here. I'm the attribute constructor!");
    }

    public String CustomDescription { get; set; }
    public String DefaultDescription { get; set; }

    public override String ToString()
    {
        return String.Format("Custom: {0}; Default: {1}", CustomDescription, DefaultDescription);
    }
}

class B 
{
    public void Laun()
    {
        Type myType = typeof(A);  // хочу получить тоже самое только через Atr
    }
}

class A
{
    [Atr]
    public static void func(int a, int b)
    {
        Console.WriteLine("a={0}  b={1}",a,b);
    }
}

您可以在Assembly上使用反射来查找其中所有具有用给定属性修饰的方法的类:

查看Assembly.GetTypes方法( http://msdn.microsoft.com/zh-cn/library/system.reflection.assembly.gettypes%28v=vs.110%29.aspx ),以枚举给定中的所有类型部件。

查看Type.GetMethods以枚举给定类型中的所有公共方法( http://msdn.microsoft.com/zh-cn/library/424c79hc%28v=vs.110%29.aspx )。

最后,查看MemberInfo.CustomAttributes( http://msdn.microsoft.com/zh-cn/library/system.reflection.memberinfo.customattributes%28v=vs.110%29.aspx ),列出所有自定义项给定方法的属性。 CustomAttributes的类型为CustomAttributeData,具有可比较的属性AttributeType。

您可以通过必须遍历的事物数量(3个嵌套循环)来猜测,这并不容易,相当复杂,更不用说SLOW了,因此您可能要装饰类的其他方面,或者在周围改变尽可能完全采用您的方法。 例如,如果您装饰类本身,则变得容易一些: 查找具有包含特定属性value的属性的所有类

查找类类型的代码最终看起来像这样(完全未经测试):

Type aType = null;
foreach (Type t in Assembly.GetExecutingAssembly().GetTypes()) {
  foreach (MethodInfo mi in t.GetMethods()) {
    foreach (CustomAttributeData cad in mi.CustomAttributes) {
      if (cad.AttributeType == typeof(Atr)) {
        aType = t;
        break;
      }
    } 
  }
}

if (aType == null) {
   // not found
} else {
   // found and aType = typeof(A) in your exmaple
}

注意:您必须确保枚举正确的类型(请参见Type类的IsClass属性),但是为了清楚起见,我将其省略。

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM