关于投掷助手的想法

joe*_*joe 6 c# exception-handling exception helper throw

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

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

用法:

    public static X operator +(X a, X b) {
        if (...) {
            return new X(...);
        }
        return ThrowInvalidOperation("+", a, b);
    }
Run Code Online (Sandbox Code Playgroud)

问题:因为运算符+必须总是返回一个值,所以我通过ThrowInvalidOperation返回一个值并使用它来调用它来修复它returnThrowInvalidOperation("+", a, b);

有许多不满 - 一个是因为我不能从返回不同类型的方法中调用它.
我希望有一种方法可以将辅助函数标记为"始终抛出异常",因此编译器会停止跟踪返回值.

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

ta.*_*.is 6

例外:

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

扔掉它:

throw MakeInvalidOperation("+", a, b);
Run Code Online (Sandbox Code Playgroud)

你的公司很好:

// 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然编写自己的Exception基于自定义类型(或InvalidOperationException基于)的类型并没有那么多代码,并且定义了一些为您格式化消息的构造函数.

减少冗余代码

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