我有以下类和方法:
public class MyGenericClass<T>
where T : class
{
}
public class MyClass
{
public TGen MyMethod<TGen>(TGen myGenClass)
where TGen : MyGenericClass<T>
where T : class
{
return myGenClass;
}
}
但是,这会报错,因为它无法解析符号 T
在我的方法中。我宁愿不必 MyMethod<TGen, T>
因为这对我来说似乎有点多余。这可能吗?
最佳答案
您必须指定 T
才能在定义中使用它。编译器无法知道 T
是什么。
所以你应该在使用它之前指定T
(在下面的方法级别,或者可能在类级别使用MyClass
):
public class MyClass
{
public TGen MyMethod<TGen, T>(TGen myGenClass)
where TGen : MyGenericClass<T>
where T : class
{
return myGenClass;
}
}
您还可以在 where 子句中使用泛型的具体实现:
public class MyClass
{
public TGen MyMethod<TGen>(TGen myGenClass)
where TGen : MyGenericClass<DateTime>
{
return myGenClass;
}
}
关于c# - 如何在泛型的 where 子句中指定泛型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10232091/