我想要转换为Func<T, string>
Func<dynamic, string>
。有可能吗?
答案 0 :(得分:6)
你走了。当您的动态值不是T
类型时,只需要决定要执行的操作:
public Func<dynamic, string> ConvertToDynamicFunc<T>(Func<T, string> typedFunc)
{
Func<dynamic, string> dynamicFunc = (input) =>
{
if (input is T)
return typedFunc((T)input);
return null; //or throw?
};
return dynamicFunc;
}
Func<int, string> typedFunc = (input) => input.ToString();
Func<dynamic, string> dynamicFunc = ConvertToDynamicFunc(typedFunc);
System.Console.WriteLine(dynamicFunc(10));//outputs "10";
System.Console.WriteLine(dynamicFunc(10.5));//outputs null since a double isn't an int (type T) or throw if you prefer;
答案 1 :(得分:4)
不确定
Func<T, string> input = ...
Func<dynamic, string> output = x => input(x);
当然,如果您使用不兼容的类型执行委托,您将获得RuntimeBinderException
。