【问题标题】:How to conditionally create obj with constraints如何有条件地创建带有约束的 obj
【发布时间】:2020-04-03 07:07:06
【问题描述】:

我有 2 个具有不同约束的类,我想在通用函数中有条件地为它们创建 obj。下面的例子。

public class Foo1<T>
 where T : class, Interface1, new()
{
   // do sth...
}

public class Foo2<T>
 where T : class, Interface2, new()
{
   //do sth...
}

public static void Create<T>()
{
    if(typeof(Interface1).IsAssignableFrom(typeof(T))
   {
       var obj = new Foo1();
       //...
   } else if (typeof(Interface2).IsAssignableFrom(typeof(T))
   {
       var obj = new Foo1();
       //...
   }
}

我收到错误“没有从 T 到 Interface1/2 的隐式引用转换”。 问题和How to conditionally invoke a generic method with constraints?类似,不过我可以找个地方补充一下(动态)。

【问题讨论】:

    标签: c# constraints


    【解决方案1】:

    您可以使用反射创建泛型类的实例。

    public static void Create<T>()
    {
       if (typeof(Interface1).IsAssignableFrom(typeof(T)))
       {
            var d1 = typeof(Foo1<>);
            Type[] typeArgs = { typeof(T) };
            var makeme = d1.MakeGenericType(typeArgs);
            object o = Activator.CreateInstance(makeme);
        }
        else if (typeof(Interface2).IsAssignableFrom(typeof(T))
        {
    
            // same for Foo2
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 2022-10-17
      • 2021-09-30
      • 2019-06-12
      相关资源
      最近更新 更多