泛型方法与动作< T>参数 [英] Generic method with Action<T> parameter

查看:117
本文介绍了泛型方法与动作< T>参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我敢肯定,这已经回答过的地方在那里,但我不能在任何地方找到它。 。希望一些仿制药大师可以帮助

 公共接口IAnimal {} 
公共类人猿:IAnimal {}

酒店的公共空间ValidateUsing< T>(动作< T>动作),其中T:IAnimal
{
猩猩猩猩=新猩猩();
动作(猩猩); //编译错误1

//这不起作用或者:
IAnimal动物=新猩猩();
动作(动物); //编译错误2
}




  1. 参数类型'猩猩'不是分配给参数类型'T'

  2. 参数类型'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
}

  1. Argument type 'Orangutan' is not assignable to parameter type 'T'
  2. 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.

这篇关于泛型方法与动作&LT; T&GT;参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆