关于投掷助手的想法

时间:2013-11-25 11:13:18

标签: c# exception exception-handling helper 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返回值并使用 {{1}调用它来解决此问题。 } return

有许多不满情绪 - 一个是因为我无法通过返回不同类型的方法来调用它 我希望有一种方法可以将辅助函数标记为“始终抛出异常”,因此编译器会停止跟踪返回值。

问:我有什么可能做到这一点?

1 个答案:

答案 0 :(得分:6)

制作例外:

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,但请记住它可能有点过分。

相关问题