我有一个Func<T, string>
我想转换为Func<dynamic, string>
. 可能吗?
问问题
396 次
2 回答
6
干得好。当您的动态值不是 type 时,只需要决定您想要做什么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;
于 2012-06-19T14:23:58.297 回答
4
当然:
Func<T, string> input = ...
Func<dynamic, string> output = x => input(x);
当然,如果你使用不兼容的类型执行委托,你会得到一个RuntimeBinderException
.
于 2012-06-19T14:22:42.133 回答