6

考虑代码:

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));

但是拥有specificFuncas Object 并且ISpecific只有通过specificFuncAsObject.GetType()

4

2 回答 2

9

T(输入类型) inFunc<T, TResult>逆变的,而不是协变的,所以这样的事情是不可能的。但是,您可以执行以下操作:

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;
于 2013-09-18T19:12:00.110 回答
4

我认为这是不可能的,请考虑以下情况:

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);
于 2013-09-18T19:09:15.080 回答