执行通用委托原型

本文关键字:原型 执行 | 更新日期: 2023-09-27 17:49:43

我正在尝试编写一个实用程序类,它将执行定义的静态方法,以尝试减少锅炉代码并增加可读性。

我的想法源于我当前的项目,将我们的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相同,方法的参数数量是否等于传入的参数数量,但感觉不安全。

我是在正确的轨道上,还是我应该寻找另一个解决方案?

这只是一个原型,因为我刚刚开始考虑重新设计

执行通用委托原型

在我看来,通过您的方法调用它的唯一的好处是将任何异常转换为SoapException。您可以更容易地这样做:

protected static T ExecuteMethod<T>(Func<T> function)
{
    try
    {
        return function();
    }
    catch
    {
        throw new SoapException("There was an error",
                                SoapException.ClientFaultCode);
    }
}

那么调用代码看起来像这样:

public CustomObject CreateItem(int id, string name)
{
    return ExecuteMethod(() => CustomObject.CreateItem(id, name));
}

(顺便说一句,我希望在实际代码中您已经对异常情况进行了一些日志记录)