C# 如何通过属性定义类型?

C# 如何通过属性定义类型?,c#,.net,types,attributes,C#,.net,Types,Attributes,一般来说,函数类A上有一个属性Atr,我想要另一个类B,输入get它注册在其中的类Atr。 在我的例子中,它应该是Type=typeof(A),只有没有A。 我希望你能明白。谢谢你的回答 下面是一个示例代码 public class Atr: Attribute { public Atr() { DefaultDescription = "hello"; Console.WriteLine("I am here. I'm the attribute

一般来说,函数类A上有一个属性Atr,我想要另一个类B,输入get它注册在其中的类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.GetTypes方法()以枚举给定程序集中的所有类型

查看Type.GetMethods以枚举给定类型()中的所有公共方法

最后,查看MemberInfo.CustomAttributes()以列出给定方法上的所有自定义属性。CustomAttributes的类型为CustomAttributeData,它具有属性AttributeType,您可以对其进行比较

正如您可以通过循环的次数(3个嵌套循环)猜测的那样,这并不容易,相当复杂,更不用说速度慢,因此您可能希望装饰类的其他方面,或者在可能的情况下完全改变方法。例如,如果您装饰类本身,它会变得更容易一些:

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

注意:您必须确保枚举了正确的类型(请参见类型类上的IsClass属性),但为了清楚起见,我省略了这一点


希望这有帮助

完全不清楚您在问什么,是否要检查
func
方法是否具有
Atr
属性?我想确定具有该属性的类的类型。例如,如果我使用属性调用任何类中的任何方法,请检查Atr determine Type.Thansk以获取idea。也许你可以得到项目名称空间?是否搜索具有与其相关属性的类的方法?
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
}