SafeRun 应该有什么参数才能正确处理以下调用场景?
SafeRun(new SomeClass(arg1, arg2));
SafeRun(new SomeOtherClass());
SafeRun(someObject.FooReturningVoid());
我尝试了以下但没有成功:(
protected void SafeAct<TResult>(Expression<Func<TResult>> expression)
protected void SafeAct(Expression<Action> expression)
SafeRun 实际上是这样做的:
protected void SafeAct<TResult>(Expression<Func<TResult>> expression)
{
try
{
Expression.Lambda<Func<TResult>>(expression).Compile()();
}
catch (Exception e)
{
ThrownException = e;
}
}
我不接受使用 lambda 表达式调用 SafeAct 的替代方法!:
I DON'T WANT THIS:
SafeRun(() => new SomeClass());
请您参考如下方法:
你不能这样做,因为这两个调用只返回对象实例,不能转换为表达式
SafeRun(new SomeClass(arg1, arg2));
SafeRun(new SomeOtherClass());
并且在 C# 中根本不允许传递 void
SafeRun(someObject.FooReturningVoid());
看看 applicable function member验证,你会看到
A function member is said to be an applicable function member with respect to an argument list A when all of the following are true:
The number of arguments in A is identical to the number of parameters in the function member declaration.
For each argument in A, the parameter passing mode of the argument (that is, value, ref, or out) is identical to the parameter passing mode of the corresponding parameter, and for a value parameter or a parameter array, an implicit conversion (Section 6.1) exists from the type of the argument to the type of the corresponding parameter
在您的情况下,不存在从参数类型( SomeClass 、 SomeOtherClass )到参数的 Expression<Action> 的隐式转换类型。只有在表达式类型和传递给方法的类型之间定义隐式转换时,您的代码才能工作。
