C# 方法 where constraint T:V
C# Method where constraint T:V
我有这个方法:
void SomeMethod<T,V>() where T:V
{
List<T> listT = getT();
List<V> listV = listT.ToList<V>()
}
它说 listT
不包含 ToList()
方法。
以上实现无效。
但它适用于具体 类,如下所示:
interface Ifoo{}
class Bar : Ifoo{}
List<Bar> bar = getBar();
List<Ifoo> bar2 = bar.ToList<Ifoo>()
这是为什么?
如何使该方法适用于那些泛型约束?
bar.ToList<Ifoo>()
之所以起作用是因为编译器可以放心Bar
实现Ifoo
.
但是,当您处于通用上下文中时,即使 T
是 V
的约束,编译器 也无法解析扩展方法(甚至尽管我们认为它应该能够做到这一点)。
您可能只想使用 Cast
...假设 T
可以 cast 到 V
:
Casts the elements of an IEnumerable to the specified type
例子
List<V> listV = getT().Cast<V>().ToList();
我有这个方法:
void SomeMethod<T,V>() where T:V
{
List<T> listT = getT();
List<V> listV = listT.ToList<V>()
}
它说 listT
不包含 ToList()
方法。
以上实现无效。 但它适用于具体 类,如下所示:
interface Ifoo{}
class Bar : Ifoo{}
List<Bar> bar = getBar();
List<Ifoo> bar2 = bar.ToList<Ifoo>()
这是为什么? 如何使该方法适用于那些泛型约束?
bar.ToList<Ifoo>()
之所以起作用是因为编译器可以放心Bar
实现Ifoo
.
但是,当您处于通用上下文中时,即使 T
是 V
的约束,编译器 也无法解析扩展方法(甚至尽管我们认为它应该能够做到这一点)。
您可能只想使用 Cast
...假设 T
可以 cast 到 V
:
Casts the elements of an IEnumerable to the specified type
例子
List<V> listV = getT().Cast<V>().ToList();