泛型方法与动作< T>参数 [英] Generic method with Action<T> parameter
问题描述
所以,我敢肯定,这已经回答过的地方在那里,但我不能在任何地方找到它。 。希望一些仿制药大师可以帮助
公共接口IAnimal {}
公共类人猿:IAnimal {}
酒店的公共空间ValidateUsing< T>(动作< T>动作),其中T:IAnimal
{
猩猩猩猩=新猩猩();
动作(猩猩); //编译错误1
//这不起作用或者:
IAnimal动物=新猩猩();
动作(动物); //编译错误2
}
- 参数类型'猩猩'不是分配给参数类型'T'
- 参数类型'IAnimal'不是分配给参数类型'T'
编辑:基于尤里和其他的建议,我可以做一些铸件,如:
公共无效ValidateUsing< T>(动作< T>动作),其中T:IAnimal
{
猩猩猩猩=新猩猩();
动作((T)(IAnimal)猩猩);
//这不起作用或者:
IAnimal动物=新猩猩();
动作((T)动物);
}
我想做的事情是调用ValidateUsing方法是这样的:
ValidateUsing(美孚);
不幸的是,如果foo的是这样的:
私人无效美孚(猩猩OBJ)
{
//做些什么
}
我要明确指定当我打电话类型ValidateUsing
ValidateUsing<&猩猩GT;(美孚);
为什么你实例化一个猩猩
如果你都应该被接受任何 IAnimal
?
公共无效ValidateUsing< T>(动作< T>动作),其中T:IAnimal,新的()
{$ b $(b T)动物=新T();
动作(动物); //编译错误2
如果你重用你的泛型参数,你不会有任何类型的问题。 ..
现在,关于为什么你的代码不能正常工作,所有你说的是,键入 T
将获得从 IAnimal
。然而,它也很容易成为一个长颈鹿
为猩猩
,所以你不能只分配猩猩
或 IAnimal
来键入 T
的参数。
So, I'm sure this has been answered somewhere out there before, but I couldn't find it anywhere. Hoping some generics guru can help.
public interface IAnimal{}
public class Orangutan:IAnimal{}
public void ValidateUsing<T>(Action<T> action) where T : IAnimal
{
Orangutan orangutan = new Orangutan();
action(orangutan); //Compile error 1
//This doesn't work either:
IAnimal animal = new Orangutan();
action(animal); //Compile error 2
}
- Argument type 'Orangutan' is not assignable to parameter type 'T'
- Argument type 'IAnimal' is not assignable to parameter type 'T'
Edit: Based on Yuriy and other's suggestions, I could do some casting such as:
public void ValidateUsing<T>(Action<T> action) where T : IAnimal
{
Orangutan orangutan = new Orangutan();
action((T)(IAnimal)orangutan);
//This doesn't work either:
IAnimal animal = new Orangutan();
action((T)animal);
}
The thing I wanted to do was call the ValidateUsing method like this:
ValidateUsing(Foo);
Unfortunately, if foo looks like this:
private void Foo(Orangutan obj)
{
//Do something
}
I have to explicitly specify the type when I call ValidateUsing
ValidateUsing<Orangutan>(Foo);
Why are you instantiating an Orangutan
if you are supposed to be accepting any IAnimal
?
public void ValidateUsing<T>(Action<T> action) where T : IAnimal, new()
{
T animal = new T();
action(animal); //Compile error 2
If you reuse your generic parameter, you won't have any type issues...
Now, with regard to why your code doesn't work, all that you're saying is that the type T
will derive from IAnimal
. However, it could just as easily be a Giraffe
as an Orangutan
, so you can't just assign an Orangutan
or IAnimal
to a parameter of type T
.
这篇关于泛型方法与动作< T>参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!