如何将采用派生类型参数的委托转换为具有基类型参数的委托
本文关键字:类型参数 转换 派生 | 更新日期: 2023-09-27 18:31:47
考虑代码:
public interface IGeneral {}
public interface ISpecific : IGeneral {}
public Func<IGeneral, String> Cast(Object specificFuncAsObject) {
var generalFunc = specificFuncAsObject as Func<IGeneral, String>;
Assert.IsNotNull(generalFunc); // <--- casting didn't work
return generalFunc;
}
Func<ISpecific, String> specificFunc = specific => "Hey!";
var generalFunc = Cast(specificFunc);
有没有办法让这样的选角工作?我知道在一般情况下,IGeneral不能投射到ISpecific。但在我的特殊情况下,我希望我能做这样的事情:
Func<IGeneral, String> generalFunc = new Func<IGeneral, String>(general => specificFunc(general as ISpecific));
但是将specificFunc
作为对象,并且仅通过specificFuncAsObject.GetType()
ISpecific
键入
Func<T, TResult>
中的T
(输入类型)是逆变的,而不是协变的,所以这样的事情是不直接可能的。但是,您可以执行以下操作:
Func<ISpecific, String> specificFunc = specific => "Hey!";
Func<IGeneral, String> generalFunc = general => specificFunc((ISpecific)general);
或者反过来:
Func<IGeneral, String> generalFunc = general => "Hey!";
Func<ISpecific, String> specificFunc = generalFunc;
我相信
这是不可能的,想想下面的情况:
class Base
{
}
class DerivedA : Base
{
}
class DerivedB : Base
{
}
使用一些方法:
string DoSomething(DerivedA myDerived)
{
}
然后,在某个地方你有代码:
Func<DerivedA, string> functionA = DoSomething;
// Let's assume this cast is possible...
Func<Base, string> functionBase = (Func<BaseB, string>) functionA;
// At this point, the signature of the function that functionBase is assigned to
// is actually `string DoSomething(DerivedA myDerived)`
functionB(new DerivedB());
// If the cast is allowed, then passing a DerivedB should be allowed, but this makes
// absolutely no sense because the function is expecting a DerivedA.
您可以做的是使用实用程序函数进行转换(如果您愿意,也可以使用as
运算符):
Func<Base, string> Convert<T>(Func<T, string> function) where T : Base
{
return x => function(x as T);
}
然后执行以下操作:
Func<DerivedA, string> functionA = DoSomething;
Func<Base, string> functionBase = Convert(functionA);