作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
考虑以下类结构:
public class Foo<T>
{
public virtual void DoSomething()
{
}
public class Bar<U> where U : Foo<T>, new()
{
public void Test()
{
var blah = new U();
blah.DoSomething();
}
}
}
public class Baz
{
}
public class FooBaz : Foo<Baz>
{
public override void DoSomething()
{
}
}
当我去使用嵌套类时,我有类似下面的东西:
var x = new FooBaz.Bar<FooBaz>();
必须指定两次似乎是多余的。我将如何创建我的类结构,以便我可以改为执行此操作:
var x = new FooBaz.Bar();
在嵌套类的 where 子句上不应该有某种方式说 U 始终是父级吗?怎么办?
更新:为上面的 DoSomething() 添加方法以解决一些评论。重要的是,当我调用 DoSomething 时,它会处理覆盖的版本。如果我只是使用 Foo 而不是 U,则会调用基本实现。
最佳答案
如果 class Bar
不需要是泛型的,你为什么要让它成为一个泛型?
这会起作用:
public class Foo<T, U> where U : Foo<T, U>
{
public class Bar
{
private T t;
private U u;
}
}
public class Baz
{
}
public class FooBaz : Foo<Baz, FooBaz>
{
}
然后
var bar = new FooBaz.Bar();
当然,所有这些都是完全抽象的,因此它可能适用于也可能不适用于实际示例。你到底想在这里实现什么?
关于c# - 在嵌套类中使用 C# 泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7932560/
我是一名优秀的程序员,十分优秀!