简体   繁体   中英

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

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(); }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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