Donc, je suis sûr que cela a déjà été répondu quelque part auparavant, mais je ne l'ai trouvé nulle part. En espérant que certains génériques puissent aider.Méthode générique avec Action <T> Paramètre
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
}
- Type d'argument 'Orangutan' est incessible au type de paramètre
- Argument type 'T' 'IAnimal' est incessible au paramètre type 'T'
Edit: Based Sur Yuriy et d'autres suggestions, je pourrais faire une certaine coulée telle que:
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);
}
La chose que je voulais faire était d'appeler la méthode ValidateUsing comme ceci:
ValidateUsing(Foo);
Malheureusement, si foo ressemble à ceci:
private void Foo(Orangutan obj)
{
//Do something
}
Je dois préciser explicitement le type quand j'appelle ValidateUsing
ValidateUsing<Orangutan>(Foo);
Merci bdukes, je viens d'utiliser Orangutan comme exemple. Probablement un mauvais. Je veux être capable d'appeler l'action avec n'importe quel IAnimal. Dans le code "réel", IAnimal est stocké comme un champ privé dans la classe. Donc, je n'instance vraiment rien. –