好吧,这是一个令人费解的 /复杂问题,就这样:
Derived
类继承自Base
类(class Derived: Base{}
)Class2
继承自Class1
(class Class2: Class1 {}
)我当前的Class1
构造函数具有:
Derived d = new Derived();
我想要的是将类型Derived
从Class2
构造函数传递到其基础(Class1
)构造函数中。那可能吗?
更完整的代码:
class Base
{
public Base() {
Console.WriteLine("Inside Base Constructor");
}
~Base() {
Console.WriteLine("Inside Base Destructor");
}
}
class Derived1: Base {
public Derived1() {
Console.WriteLine("Inside The Derived1 Constructor");
}
~Derived1() {
Console.WriteLine("Inside The Derived1 Destructor");
}
}
class Derived2: Base {
public Derived2() {
Console.WriteLine("Inside The Derived2 Constructor");
}
~Derived2() {
Console.WriteLine("Inside The Derived2 Destructor");
}
}
class Class1
{
protected int a, b;
public Class1() {
a = 0;
b = 0;
Derived1 obj=new Derived1();
Console.WriteLine("Inside base class default constructor");
}
public Class1(int a, int b, Derived1) {
this.a = a;
this.b = b;
Derived1 obj=new Derived1();
Console.WriteLine("Inside base class parameterized constructor");
}
}
class Class2: Class1 {
int c;
public Class2(int a, int b, int c): base(a, b, Derived1) {
this.c = c;
Console.WriteLine("Inside derived class parametrized constructor");
}
}
也就是说,我想通过base(a, b, Derived1)
来传递Class2
的构造函数/定义,无论是Class1
还是Derived1
,Derived2
都会是什么类型。
希望我已经阐明了这个 convolulated /复杂问题。
答案 0 :(得分:2)
您还可以使用下面使用的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
我希望有帮助。