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 を持ち、ISpecifictype を介してのみ持つ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 に答える