简体   繁体   English

动态创建一个泛型类型,该类型使用类型本身作为泛型参数

[英]Dynamically create a generic type which use the type itself as generic parameter

Here a dummy code to explain my problem: 这里有一个虚拟代码来解释我的问题:

public class A<TX, TA> where TA : A<TX, TA>
{

}

public void Do()
{
   var doy = typeof(A<,>).MakeGenericType(typeof(string), null/*??????*/));
}

How can I make a type from my generic type, if I can't identifty my type to use it as parameter? 如果我无法识别我的类型以将其用作参数,如何从我的泛型类型中创建类型?

Thanks for your help. 谢谢你的帮助。

Edit, example of doing it statically: 编辑,静态执行的示例:

public abstract class A<TX, TA> where TA : A<TX, TA>
{
    public TA ChainMethod()
    {
        return (TA)this;
    }
}

public class AConcrete : A<string, AConcrete>
{
    public AConcrete OtherMethod()
    {
    return this;
    }
}

public class App
{
    public static void Start()
    {
    new AConcrete().ChainMethod().ChainMethod().OtherMethod();
    }
}

You need to design your class hierarchy. 您需要设计类层次结构。 It seems like it's not quite there yet. 好像还没到那里。 Please check out this example, hope it will give you an idea: 请看看这个例子,希望它会给你一个想法:

abstract class BaseBuilder<TBrick>
{
    public BaseBuilder<TBrick> AddBrick(TBrick brick)
    {
        // ...
        return this;
    }
}

class Builder : BaseBuilder<ConcreteBrick>
{
    public Builder AddRoof()
    {
        // ...
        return this;
    }

    public new Builder AddBrick(ConcreteBrick brick) 
    {
        base.AddBrick(brick);
        return this;
    }
}

And it will look like this: 它看起来像这样:

new Builder()
    .AddBrick(new ConcreteBrick())
    .AddBrick(new ConcreteBrick())
    .AddRoof();

I think you won't be able to chain calls with inheritance if you don't override methods with new keyword like I suggested. 如果你不像我建议的那样使用new关键字覆盖方法,我认为你将无法使用继承链接调用。 Though you can implement things easily if you give up an idea of chaining calls. 虽然如果你放弃链接呼叫的想法,你可以轻松实现。

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

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