根据泛型类型将不同的枚举传递给方法

时间:2013-12-02 12:33:09

标签: c# generics enums

是否可以将enum作为参数传递给泛型函数?在下面的代码中,我希望CreateInstance函数根据给定的泛型类型获取枚举参数。示例代码更好地解释了这个问题:

public class DrivedA
{
    public string myfieldA{get;set;}
    public enum DrivedA_Attributes {
       A,
       B,
       C,
    }

    public void Set(params DerivedClassExtraParameters<DrivedA>[] p)
    {
        //some code
    }
}

public class DrivedB
{
     public string myfieldB { get; set; }
     public enum DrivedB_Attributes
     {
         D,
         E,
         F,
     }

     public void Set(params DerivedClassExtraParameters<DrivedB>[] p)
     {
         //some code
     }
 }

 public class DerivedClassExtraParameters<T>
 {
     internal object myFieldD;
     internal string myName;
     static public DerivedClassExtraParameters<T> CreateInstance(Enum name,  object value)
     {
         DerivedClassExtraParameters<T> instance = new DerivedClassExtraParameters<T>();
         instance.myFieldD = value;
         instance.myName = name.ToString();
         return instance;
     }
 }

 public class TestClass
 {
     public static void Main(string[] args)
     {
         DerivedClassExtraParameters<DrivedB> pB = DerivedClassExtraParameters<DrivedB>.CreateInstance(DrivedB.DrivedB_Attributes.D,"1");

         DrivedB b = new DrivedB();
         b.Set(pB);

         //Line #X, I want this line to give error since DerivedClassExtraParameters<DrivedA>.CreateInstance function should get DrivedA.DrivedA_Attributes enum as parameter, not DrivedB.DrivedB_Attributes.
         DerivedClassExtraParameters<DrivedA> pA =      DerivedClassExtraParameters<DrivedA>.CreateInstance(DrivedB.DrivedB_Attributes.D, "1");

         DrivedA a = new DrivedA();
         a.Set(pA);
     }

 }

1 个答案:

答案 0 :(得分:0)

您正在以错误的方式使用泛型。你应该试试这个。

 public class DerivedClassExtraParameters<T>
 {
     internal T myFieldD;
     internal string myName;
     static public DerivedClassExtraParameters<T> CreateInstance(T value)
     {
         DerivedClassExtraParameters<T> instance = new DerivedClassExtraParameters<T>();
         instance.myFieldD = value;
         instance.myName = value.GetType().Name;
         return instance;
     }
 }

您甚至不需要静态CreateInstance方法。你可以这样做

public class DerivedClassExtraParameters<T>
     {
         internal T myFieldD;
         internal string myName;

         public DerivedClassExtraParameters(T value)
         {
              myFieldD = value;
              myName = value.GetType().Name;
         }
     }