C# 如何通过它们的属性到达类

C# 如何通过它们的属性到达类,c#,C#,我有很多类和一个自定义属性类。我的所有类都有在我的属性中定义的唯一id。我在列表中随机添加我的类的实例。如何通过检查属性来识别哪个类 基本上 我有一个属性类 public class myAtt : Attribute { public int id; public myAtt(int id){ this.id = id; } } 我有一个枚举 public enum myEnum { IT_IS_A_CLASS, IT_IS_B_CLASS, IT_IS_C_

我有很多类和一个自定义属性类。我的所有类都有在我的属性中定义的唯一id。我在列表中随机添加我的类的实例。如何通过检查属性来识别哪个类

基本上

我有一个属性类

public class myAtt : Attribute
{
   public int id;

   public myAtt(int id){ this.id = id; }
}
我有一个枚举

public enum myEnum
{
   IT_IS_A_CLASS,
   IT_IS_B_CLASS,
   IT_IS_C_CLASS
}
具有此属性的一组类

[myAtt((int)myEnum.IT_IS_A_CLASS)]
public class A
{
   
}

[myAtt((int)myEnum.IT_IS_B_CLASS)]
public class B
{
   
}

[myAtt((int)myEnum.IT_IS_C_CLASS)]
public class C
{
   
}
我有一个线程函数,可以从另一个线程填充的队列中取出项目。不要介意线程安全

while(true)
{
   var temp = myQ.Dequeue();
   switch((myEnum)temp.id)   <-- I basicly want to this entire switch become one-liner.
   {
      case myEnum.IT_IS_A_CLASS:  aFunction(new A()); break;
      case myEnum.IT_IS_B_CLASS:  aFunction(new B()); break;
      case myEnum.IT_IS_C_CLASS:  aFunction(new C()); break;
      .
      .
      .
      case myEnum.IT_IS_Z_CLASS:  aFunction(new Z()); break;
   }
}

要回答您的问题,以下内容将起作用。然而,正如对您的问题的评论所表明的,这确实违背了多态性的整体概念

在这种情况下也会有很多问题,比如当多个类共享同一属性时会发生什么

此外,如果您真的需要在运行时动态激活类,您可以简单地使用
队列
,而不是使用自定义的emum

public static object magicFunction(myEnum value)
{
    return Activator.CreateInstance(
        Assembly.GetExecutingAssembly()
            .DefinedTypes
            .FirstOrDefault(x => x.GetCustomAttribute<myAtt>()?.id == (int)value));
}
公共静态对象magicFunction(myEnum值)
{
返回Activator.CreateInstance(
Assembly.getExecutionGassembly()
.定义类型
.FirstOrDefault(x=>x.GetCustomAttribute()?.id==(int)值);
}

这是否回答了您的问题?但是请注意,如果您试图从头开始发明多态性,那么您应该真正使用继承和虚拟方法?26重载或这些类在继承树中吗?为什么不使用继承?那你就知道哪个班是哪个班了。你将能够以这种方式查看所有的子类,反过来,你的1行是否理解你试图做什么的机制,我不明白你为什么要这样做。要知道对象的类型,只需在类或接口上使用“is”。您可以使用。GetType()或type()。属性名称不必具有匹配的属性类型。告诉我们你为什么喜欢这样做,也许答案会更有用
public static object magicFunction(myEnum value)
{
    return Activator.CreateInstance(
        Assembly.GetExecutingAssembly()
            .DefinedTypes
            .FirstOrDefault(x => x.GetCustomAttribute<myAtt>()?.id == (int)value));
}