我知道这个问题听起来有点奇怪。对不起,有困难试图到达我想要的地方,甚至解释它。为简单起见,我有一个Func<T>
参数的方法。但我并不总是将无参数的 Action 传递给该方法,我需要变化参数的数量,而我正试图找到一种方法来避免重载我的方法每次需要的参数数量增加
这是我的泛型类,我需要重载 GetInstance
方法:
public class MethodResult<T>
{
public T Result { get; set; }
public bool IsResulted { get; set; }
public Exception Error { get; set; }
private MethodResult() { }
public static MethodResult<T> GetInstance<T>(Func<T> method)
{
MethodResult<T> obj = new MethodResult<T>();
try
{
obj.Result = method();
obj.IsResulted = true;
obj.Error = null;
}
catch (Exception ex)
{
obj.Result = default(T);
obj.IsResulted = false;
obj.Error = ex;
}
return obj;
}
public static MethodResult<T> GetInstance<T, T1>(Func<T1, T> method, T1 param1)
{
MethodResult<T> obj = new MethodResult<T>();
try
{
obj.Result = method(param1);
obj.IsResulted = true;
obj.Error = null;
}
catch (Exception ex)
{
obj.Result = default(T);
obj.IsResulted = false;
obj.Error = ex;
}
return obj;
}
}
以下是展示我如何使用它的示例:
public static void Main(string[] args)
{
var x = MethodResult<int>.GetInstance(IntResult, 5);
Console.WriteLine("Result: {0}, IsResulted: {1}, ErrorMessage: {2}", x.Result, x.IsResulted, (x.Error == null ? "null" : x.Error.Message));
var y = MethodResult<string>.GetInstance(SayHello);
Console.WriteLine("Result: {0}, IsResulted: {1}, ErrorMessage: {2}", y.Result, y.IsResulted, (y.Error == null ? "null" : y.Error.Message));
Console.Read();
}
public static int IntResult(int x) { return x + 1; }
public static int IntResult(int x, int y) { return x + y; }
public static string SayHello() { return "Hello world!"; }
为了能够使用IntResult(int x, int y)
我必须使用signiture 重载 GetInstance
方法:
public static MethodResult<T> GetInstance<T, T1, T2>(Func<T1, T2, T> method, T1 param1, T2 param2)
很明显,这会非常耗时,因为它已经很烦人了。有没有办法避免那么多重载?
答案 0 :(得分:1)
您可以传递一个无参数匿名 delegate
来调用您想要指向的方法,而不是传递要调用的函数和参数。只需删除 GetInstance 的任何重载,只需保留:
public static MethodResult<T> GetInstance(Func<T> method)
{
MethodResult<T> obj = new MethodResult<T>();
try
{
obj.Result = method();
obj.IsResulted = true;
obj.Error = null;
}
catch (Exception ex)
{
obj.Result = default(T);
obj.IsResulted = false;
obj.Error = ex;
}
return obj;
}
然后将其称为:
int n = 1;
var x = MethodResult<string>.GetInstance(() => SayHello());
var y = MethodResult<string>.GetInstance(() => IntResult(2));
var z = MethodResult<int>.GetInstance(() => IntResult(n, 9));