[英]Dynamically create a generic type which use the type itself as generic parameter
这里有一个虚拟代码来解释我的问题:
public class A<TX, TA> where TA : A<TX, TA>
{
}
public void Do()
{
var doy = typeof(A<,>).MakeGenericType(typeof(string), null/*??????*/));
}
如果我无法识别我的类型以将其用作参数,如何从我的泛型类型中创建类型?
谢谢你的帮助。
编辑,静态执行的示例:
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();
}
}
您需要设计类层次结构。 好像还没到那里。 请看看这个例子,希望它会给你一个想法:
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;
}
}
它看起来像这样:
new Builder()
.AddBrick(new ConcreteBrick())
.AddBrick(new ConcreteBrick())
.AddRoof();
如果你不像我建议的那样使用new
关键字覆盖方法,我认为你将无法使用继承链接调用。 虽然如果你放弃链接呼叫的想法,你可以轻松实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.