Creating an instance of a generic class from a static method in a derived class

I have a class in C # with a template and a static method similar to

class BClass<T>
{
  public static BClass<T> Create()
  {
    return new BClass<T>();
  }
 }

From this I get the class and set the template parameter to the base class

class DClass : BClass<int> { }

The problem occurs when I try to use the static method to instantiate D

class Program
{
  static void Main(string[] args)
  {
    DClass d = DClass.Create();
  }
}

Gives a compiler error "Unable to implicitly convert the type" Test.BClass <int> "to" Test.DClass ".

Adding the following list throws a runtime exception at runtime.

DClass d = (DClass)DClass.Create();

Is there a succint method that allows a static method to instantiate a derived class? Ideally, I would like to get the C ++ equivalent of typedef, and I don't need the syntax below (which works).

BClass<int> d = DClass.Create();
+5
3

, ,, . , .NET- , , , .

class BClass<T, TSelf> where TSelf: BClass<T, TSelf>, new() {
    public static TSelf Create() {
        return new TSelf();
    }
}

class DClass: BClass<int, DClass> {}

class Program {
    static void Main(string[] args) {
        DClass d = DClass.Create();
    }
}
+5

, , DClass BClass<int>. , . , DClass BClass<int>. , DClass.Create(); BClass<int>, DClass ( ).

. , :

class Rectangle {
    static Rectangle Create() {
        return new Rectangle();
    }
}

class Square : Rectangle { }

// code elsewhere
var shape = Square.Create(); // you might want this to return a square,
                             // but it just going to return a rectangle

- , , - Create :

static TClass Create<TClass>() where TClass : BClass<T>, new() {
    return new TClass();
}

// code elsewhere
var shape = DClass.Create<DClass>();

( , DClass). Create , factory.

+7
class BClass<T>
    {
        public static T1 Create<T1, T2>() where T1 : BClass<T2>, new()
        {
            return new T1();
        }
    }

    class DClass : BClass<int> { }

    class Program
    {
        static void Main(string[] args)
        {
            DClass d = DClass.Create<DClass, int>();
        }
    }
+1

All Articles