【问题标题】:Executing generic delegate prototype执行通用委托原型
【发布时间】: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


【解决方案1】:

在我看来,通过您的方法调用它的唯一好处是将任何异常转换为 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));
}

(顺便说一句,我希望在实际代码中你有一些异常情况的日志记录。)

【讨论】:

  • 哦——太好了。我一直在努力弄清楚它是如何工作的,但是您的示例很好地清除了这一点,并且该模式似乎确实很适合实现我整理服务方法的目标。是的,我将实施一个更强大的异常案例处理解决方案——这只是为了测试,但对她来说可能太多了。谢谢乔恩
猜你喜欢
  • 2012-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多