Is generic constructor in non-generic class supported?

后端 未结 3 1457
执念已碎
执念已碎 2020-12-03 09:27

Is it not supported, is it supported but I have to do some tricks?

Example:

class Foo
{
  public Foo(Func f1,Func

        
3条回答
  •  一个人的身影
    2020-12-03 10:21

    Generic constructors are not supported, but you can get around this by simply defining a generic, static method that returns a new Foo:

    class Foo
    {
      public static Foo CreateFromFuncs(Func f1,Func f2)
      {
         ...
      }
    }
    

    which is used like this:

    // create generic dependencies
    var func1 = new Func(...);
    var func2 = new Func(...);
    
    // create nongeneric Foo from dependencies
    Foo myFoo = Foo.CreateFromFuncs(func1, func2);
    

提交回复
热议问题