我试着写,将执行定义的静态方法,试图减少对锅炉的代码和增加可读性的实用程序类。执行泛型委托原型
我的想法从我目前的WCF服务,所有方法都排除了服务请求的统一锅炉代码模式改写我们的aspx web服务的项目茎。静态方法目前不存在于我们现有的对象中,因为大多数逻辑都在Web服务方法本身内部,但应该易于转移。
什么我到目前为止下面是一个例子。
[DataContract]
public CustomObject CreateItem(int id, string name)
{
return ExecuteMethod<CustomObject>(CustomObject.CreateItem, id, name);
}
protected static T ExecuteMethod<T>(Delegate methodToExecute, params object[] parameters)
{
// Do some basic logging
// Authenticate user
try
{
if (methodToExecute == null)
{
throw new Exception();
}
if (methodToExecute.Method.ReturnType != typeof(T))
{
throw new Exception();
}
if (methodToExecute.Method.GetParameters().Length != parameters.Length)
{
throw new Exception();
}
return (T)methodToExecute.Method.Invoke(methodToExecute, parameters);
}
catch
{
throw new SoapException("There was an error", SoapException.ClientFaultCode);
}
}
public class CustomObject
{
[DataMemeber]
public int Id { get; set; }
[DataMember]
pubic string Name { get; set; }
internal static Delegate CreateItem = new Func<int, string, CustomObject>(
(id, name) =>
{
return new CustomObject() { Id = 1, Name = name };
}
);
}
我上面的示例应该说明我正在努力实现的目标。但是,我觉得这种方法到目前为止失败的原因是传递给泛型方法的参数没有输入,并可能导致运行时错误(对于返回类型和参数类型)
我已经添加了一些基本检查,如检查的MethodInfo的返回类型为同一类型为T和方法的参数个数等于传入参数的数量,但并不感到“安全”的。
上午我在正确的轨道,或者我应该考虑的替代方案?
这只是目前的原型,因为我刚开始考虑重新设计。
什么时候MyHelpers.ExecMethod(MyMethod,params)'比'MyMethod(params)'更容易? – 2011-04-12 15:35:47