[英]C# cannot cast T to T
I have a generic collection MyCollection<T>
that I've made, and everything works fine except this new function Apply
that I'm adding: 我有一个我已经制作的通用集合MyCollection<T>
,一切正常,除了这个新函数Apply
我正在添加:
class MyCollection<T> {
T value;
public MyCollection(T starter) { value = starter; }
public MyCollection<S> Apply<T, S>(Func<T, S> function) {
return new MyCollection<S>(function(value)); // error in function(value)
}
}
This gives me an error I've never seen before: 这给了我一个我以前从未见过的错误:
Argument 1: cannot convert from 'T' to 'T [C:\folder\code.cs (line number)]'
What are the two T
types? 这两种T
型有哪些? What's wrong with the conversion I'm attempting? 我正在尝试的转换有什么问题?
You problem is that the type parameter T in 你的问题是类型参数T in
class MyCollection<T>
is not the same type parameter as T in 与T in的类型参数不同
Apply<T, S>
so your function
takes another type than the type of value
所以你的function
采用的不是类型的value
if you change 如果你改变
Apply<T, S>
to 至
Apply<S>
your code will compile 你的代码将编译
One T comes from MyCollection<T>
and one from Apply<T, S>
. 一个T来自MyCollection<T>
,一个来自Apply<T, S>
。 Apply<S>
should suffice. Apply<S>
就足够了。
It's trying to cast the generic type of the class to the generic type of the method. 它试图将类的泛型类型转换为方法的泛型类型。 Remove the T
from the signature of the Apply
method. 从Apply
方法的签名中删除T
class MyCollection<T> {
T value;
public MyCollection(T starter) { value = starter; }
public MyCollection<S> Apply<S>(Func<T, S> function) {
return new MyCollection<S>(function(value));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.