简体   繁体   English

如何在当前类型中使用泛型

[英]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)? 我应该怎么放,而不是ThisInstanceType为了使用泛型与“此”(当前子实例)的类型?

I cannot change the declaration of Parent.DoSomething() . 我无法更改Parent.DoSomething()的声明。 It cannot be void DoSomething<T>() . void DoSomething<T>()不能为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(); 公共接口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[] {});

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

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