c# - 无效泛型类型参数的最佳异常(exception)

标签 c# generics exception

我目前正在为 UnconstrainedMelody 编写一些代码它具有与枚举有关的通用方法。

现在,我有一个带有一堆方法的静态类,这些方法旨在与“标志”枚举一起使用。我不能将其添加为约束...因此它们也可能会被其他枚举类型调用。在那种情况下,我想抛出一个异常,但我不确定抛出哪一个。

只是为了使这个具体化,如果我有这样的东西:

// Returns a value with all bits set by any values
public static T GetBitMask<T>() where T : struct, IEnumConstraint
{
    if (!IsFlags<T>()) // This method doesn't throw
    {
        throw new ???
    }
    // Normal work here
}

最好抛出什么异常? ArgumentException 听起来合乎逻辑,但它是一个类型 参数而不是一个普通参数,这很容易混淆事情。我应该引入我自己的 TypeArgumentException 类吗?使用 InvalidOperationExceptionNotSupportedException?还有什么吗?

宁愿不为此创建我自己的异常(exception),除非它显然是正确的做法。

最佳答案

NotSupportedException 听起来它很适合,但文档明确指出它应该用于不同的目的。来自 MSDN 类评论:

There are methods that are not supported in the base class, with the expectation that these methods will be implemented in the derived classes instead. The derived class might implement only a subset of the methods from the base class, and throw NotSupportedException for the unsupported methods.

当然,有一种方法可以让 NotSupportedException 显然足够好,特别是考虑到它的常识性含义。话虽如此,我不确定它是否恰到好处。

考虑到 Unconstrained Melody 的目的...

There are various useful things that can be done with generic methods/classes where there's a type constraint of "T : enum" or "T : delegate" - but unfortunately, those are prohibited in C#.

This utility library works around the prohibitions using ildasm/ilasm ...

...尽管在创建自定义 Exceptions 之前我们必须满足沉重的举证责任,但似乎需要一个新的 Exception。像 InvalidTypeParameterException 这样的东西可能在整个库中都有用(或者可能没有用 - 这肯定是一种边缘情况,对吧?)。

客户是否需要能够将其与 BCL 异常区分开来?什么时候客户可能会不小心使用普通的 enum 调用它?您将如何回答 What factors should be taken into consideration when writing a custom exception class? 的已接受答案所提出的问题?

关于c# - 无效泛型类型参数的最佳异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1412598/

相关文章:

C# 列表框绑定(bind)到实体 "Entity Framework"

java - 如何确定注入(inject)的CDI bean的parameterizedType的具体类型

java - 打印异常的堆栈跟踪

c# - 无法跟踪实体类型的实例,因为已跟踪具有相同键的该类型的另一个实例

c# - 如何替换许多基于文本的文件中的变量值

generics - 如何在 Kotlin 中将多个 Upper Bounds 语法与委托(delegate)语法结合起来

python - 将参数从批处理文件传递到 Python

c++如何用泛型异常对象处理所有类型的异常?

c# - 在哪里可以找到 Prism.UnityExtensions

ios - 无法推断网络层的通用参数 'T'