简体   繁体   中英

How to use generics with the current type

I have this base class:

public abstract class Parent {
    public void DoSomething() {
        var c=new GenericClass<**ThisInstanceType**>();
        c.DoYourThing();
    }
}

What should I put instead ThisInstanceType in order to use generics with the type of "this" (the current child instance)?

I cannot change the declaration of Parent.DoSomething() . It cannot be void DoSomething<T>() .

If you make your abstract class generic, you can implement it like this:

public abstract class Parent<T> where T : Parent<T> {
    public void DoSomething() {
        var c = new GenericClass<T>();
        c.DoYourThing();
    }
 }

public class Child : Parent<Child> {}

You could do:

public abstract class Parent<T> : IParent
{
    public void DoSomething() {
        var c=new GenericClass<T>();
        c.DoYourThing();
    }
}

public sealed class Child : Parent<Child>
{
}

and if necessary you could add:

public interface IParent { void DoSomething(); }

BTW: If you include the full complete real life example, I might be able to give you a better solution

The other solution would be to use reflection to get the proper type and call the method at runtime...

If you really cannot design it properly, you could do it via reflection. I hesitate to suggest that, as you really should be redesigning your interface, but:

Type t = typeof(GenericClass<>).MakeGenericType(this.GetType());
object c = Activator.CreateInstance(t);
c.InvokeMember("DoYourThing", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, c, new object[] {});

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