简体   繁体   English

C#在基类中创建派生类的实例

[英]C# create instance of the derived class in the base class

I have the following set up: 我有以下设置:

public abstract class A
{
    public void f()
    {
        //Want to make an instance of B or C here
        //A bOrC = new ?
    }
    public abstract void f2();
}
public class B : A { public override void f2(){} }
public class C : A { public override void f2(){} }

Is this possible? 这可能吗? If so how? 如果是这样的话?

Edit: bOrC needs to be the type of the particular derived class f() is called from 编辑: bOrC需要是从中调用的特定派生类f()的类型

I can think of two ways to solve this issue. 我可以想出两种方法来解决这个问题。 One uses generics and the other just requires an abstract method. 一个使用泛型,另一个只需要一个抽象方法。 First the simple one. 首先是简单的。

public abstract class A
{
    public void f()
    {
        A bOrC = newInstance();
    }
    public abstract void f2();
    protected abstract A newInstance();
}
public class B : A {
    public override void f2(){}
    public override A newInstance(){
        return new B();
    }
}
public class C : A {
    public override void f2(){}
    public override A newInstance(){
        return new C();
    }
}

And now with generics 现在有了泛型

public abstract class A<T> where T : A, new()
{
    public void f()
    {
        A bOrC = new T();
    }
    public abstract void f2();
}
public class B : A<B> {
    public override void f2(){}
}
public class C : A<C> {
    public override void f2(){}
}

你可以使用Activator.CreateInstance(this.GetType());

This is not possible, and would lead to some weird consequences if it was. 这是不可能的,如果是这样的话会导致一些奇怪的后果。 However, there is an easy work around rendering code that is easy to read. 但是,有一个易于阅读的渲染代码的简单工作。

public abstract class A
{
    public void f()
    {
        //Want to make an instance of B or C here
        //A bOrC = new ?
        A bOrC = Create();
    }
    public abstract void f2();
    public abstract A Create();
}
public class B : A {
  public override void f2(){}
  public override A Create() { return new B(); }
}
public class C : A {
  public override void f2(){}
  public override A Create() { return new C(); }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM