简体   繁体   English

如何通过属性定义类型?

[英]How to define Type through Attributes?

In general, there is an attribute Atr over function class A, I want another class B, Type get the class in which it is registered Atr. 通常,在函数类A上有一个属性Atr,我想要另一个类B,类型获取在其中注册了Atr的类。 in my case it should be Type = typeof (A) only without A. I hope you get the idea. 在我的情况下,它应该仅是Type = typeof(A)而没有A。希望您能理解。 Thanks for answers. 感谢您的回答。

Here is a sample code. 这是示例代码。

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

You can use reflection on the Assembly to find all of the classes that have a method in them that are decorated with a given attribute: 您可以在Assembly上使用反射来查找其中所有具有用给定属性修饰的方法的类:

Look at the Assembly.GetTypes method ( http://msdn.microsoft.com/en-us/library/system.reflection.assembly.gettypes%28v=vs.110%29.aspx ) for enumerating all the types in a given assembly. 查看Assembly.GetTypes方法( http://msdn.microsoft.com/zh-cn/library/system.reflection.assembly.gettypes%28v=vs.110%29.aspx ),以枚举给定中的所有类型部件。

Look at Type.GetMethods to enumerate all the public methods in a given type ( http://msdn.microsoft.com/en-us/library/424c79hc%28v=vs.110%29.aspx ). 查看Type.GetMethods以枚举给定类型中的所有公共方法( http://msdn.microsoft.com/zh-cn/library/424c79hc%28v=vs.110%29.aspx )。

And then finally, look at MemberInfo.CustomAttributes ( http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.customattributes%28v=vs.110%29.aspx ) to list out all the custom attributes on a given method. 最后,查看MemberInfo.CustomAttributes( http://msdn.microsoft.com/zh-cn/library/system.reflection.memberinfo.customattributes%28v=vs.110%29.aspx ),列出所有自定义项给定方法的属性。 CustomAttributes is of type CustomAttributeData, which has property AttributeType which you can compare on. CustomAttributes的类型为CustomAttributeData,具有可比较的属性AttributeType。

As you can guess by the number of things you have to loop over (3 nested loops), it will not be easy, fairly convoluted, not to mention SLOW, so you might want to decorate some other aspect of your class, or change around your approach entirely if possible. 您可以通过必须遍历的事物数量(3个嵌套循环)来猜测,这并不容易,相当复杂,更不用说SLOW了,因此您可能要装饰类的其他方面,或者在周围改变尽可能完全采用您的方法。 For example, if you decorate the class itself, it becomes a little easier: Find all classes with an attribute containing a specific property value . 例如,如果您装饰类本身,则变得容易一些: 查找具有包含特定属性value的属性的所有类

The code to find the class type ends up looking something like this (completely untested): 查找类类型的代码最终看起来像这样(完全未经测试):

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
}

Note: You have to make sure you enumerate over the right types (see IsClass property on Type class), but I left that out for clarity. 注意:您必须确保枚举正确的类型(请参见Type类的IsClass属性),但是为了清楚起见,我将其省略。

Hope this helps! 希望这可以帮助!

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

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