考虑代码:
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
as Object 并且ISpecific
只有通过specificFuncAsObject.GetType()