2015-05-05 34 views
0

我有几种方法,其参数是一个派生类型:Func键与导出参数

bool Method1(ChildType1); 
bool Method2(ChildType2); 

随着ChildType1和从ParentType的ChildType2 heritating。

我希望有一个委托,它可以接受方法1或方法2,但得到的编译错误:

Func<ParentType, bool> MyDelegate = Method1; 

错误1,没有超载的“方法一”比赛代表“Func键< ParentType的, 布尔>”

有没有办法避免这种情况?

+1

使用委托covarianc/contravariance。请参阅https://msdn.microsoft.com/en-us/library/ms173174.aspx – Maarten

+1

@Marteen委托在它们的* return *类型中是协变的(并且在它们的参数中是逆变的)。 OP需要协变参数,这是不可能的。 – dcastro

+0

你为什么要这么做?底层需求是什么? – Enigmativity

回答

4

想想,如果这是有可能将会发生什么:

Func<ParentType, bool> MyDelegate = Method1; 

//Method1 does not accept a parameter of type ChildType2, but MyDelegate does 
MyDelegate(new ChildType2()); 

这并不是出于同样的原因,为什么你不能投List<Dog>List<Animal>实例工作 - 因为那么你可以调用animals.Add(cat),这将不得不在运行时抛出异常,因为猫不能被添加到狗列表中。