Вы также можете использовать ключевое слово typeof
, используемое ниже:
class Class2 : Class1
{
int c;
public Class2(int a, int b, int c) : base(a, b, typeof(Derived1))
{
this.c = c;
Console.WriteLine("Inside derived class parametrized constructor");
}
}
void Main()
{
Class2 c2 = new Class2(1,2, 3);
}
Или напишите более общую форму, используя C # generics , например:
class Class1<T> where T: new()
{
protected int a, b;
public Class1()
{
a = 0;
b = 0;
T obj = new T();
Console.WriteLine("Inside base class parameterized constructor, with {0}", typeof (T));
}
public Class1(int a, int b)
{
this.a = a;
this.b = b;
T obj = new T();
Console.WriteLine("Inside base class parameterized constructor");
}
}
class Class2<T> : Class1<T> where T: new()
{
int c;
public Class2(int a, int b, int c) : base(a, b)
{
this.c = c;
Console.WriteLine("Inside derived class parametrized constructor");
}
}
void Main()
{
var c2 = new Class2<Derived1>(1, 2, 3);
Console.WriteLine("-----");
var c2_2 = new Class2<Derived2>(1, 2, 3);
}
И вывод будет:
Inside Base Constructor
Inside The Derived1 Constructor
Inside base class parameterized constructor, with Derived1
Inside derived class parametrized constructor
-----
Inside Base Constructor
Inside The Derived2 Constructor
Inside base class parameterized constructor, with Derived2
Inside derived class parametrized constructor
Надеюсь, это поможет.