【发布时间】:2023-03-28 09:38:01
【问题描述】:
我正在尝试编写一个实用程序类,该类将执行已定义的静态方法,以尝试减少锅炉代码并提高可读性。
我的想法源于我目前将我们的 aspx Web 服务重写为 WCF 服务的项目,其中所有方法都具有统一的锅炉代码模式,不包括服务请求。静态方法目前不存在于我们现有的对象上,因为大多数逻辑都存在于 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)更容易?
标签: c# generics delegates prototype reusability