【问题标题】:Thoughts on throw helpers关于投掷助手的思考
【发布时间】:2013-12-10 01:00:38
【问题描述】:

为了减少冗余代码,我有一些 throw 辅助方法:

protected static X ThrowInvalidOperation(string operation, X a, X b) {
    throw new InvalidOperationException("Invalid operation: " + a.type.ToString() + " " + operation + " " + b.type.ToString());
}

用法:

    public static X operator +(X a, X b) {
        if (...) {
            return new X(...);
        }
        return ThrowInvalidOperation("+", a, b);
    }

问题:因为运算符+ 必须始终返回一个值,我通过使ThrowInvalidOperation 返回一个值并使用return@ 调用它来解决这个问题987654326@

有很多缺点 - 一个是因为我不能从返回不同类型的方法中调用它。
我希望有一种方法可以将辅助函数标记为“总是抛出异常”,这样编译器就会停止跟踪返回值。

问:我需要哪些可能性才能完成这项工作?

【问题讨论】:

  • 您是否考虑过在帮助程序中创建异常,同时将其抛出到运算符实现中?例如。 throw NewInvalidOperationException(...);

标签: c# exception exception-handling helper throw


【解决方案1】:

例外:

protected static Exception MakeInvalidOperation(string operation, X a, X b)
{
    return new InvalidOperationException(
        "Invalid operation: " + a.type + " " + operation + " " + b.type);
}

然后扔掉它:

throw MakeInvalidOperation("+", a, b);

你们相处得很好:

// Type: Microsoft.Internal.Web.Utils.ExceptionHelper
// Assembly: WebMatrix.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// MVID: 3F332B40-45DB-42E2-A4ED-0826DE223A79
// Assembly location: C:\Windows\Microsoft.NET\assembly\GAC_MSIL\WebMatrix.Data\v4.0_1.0.0.0__31bf3856ad364e35\WebMatrix.Data.dll

using System;

namespace Microsoft.Internal.Web.Utils
{
    internal static class ExceptionHelper
    {
        internal static ArgumentException CreateArgumentNullOrEmptyException(string paramName)
        {
            return new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, paramName);
        }
    }
}

尽管编写您自己的自定义基于Exception 的类型(或基于InvalidOperationException)并定义一些为您格式化消息的构造函数的代码并不多。

减少冗余代码

当我听到这个时,我认为 AOP PostSharp 很好地实现了它。如果你有很多冗余代码,你应该考虑使用 AOP,但请记住它可能有点矫枉过正。

【讨论】:

  • 只有两种可能:我的工作太笨了我做这份工作的时间太长了 - 解决方案远非简单......
  • @joe 第三个相互包容的解决方案怎么样? :)
  • @taspeotis:你说得对——现在最好不要离开家
猜你喜欢
  • 1970-01-01
  • 2010-09-18
  • 1970-01-01
  • 1970-01-01
  • 2010-12-09
  • 2014-05-01
  • 2011-09-05
  • 2011-07-19
  • 2010-10-19
相关资源
最近更新 更多