-3

我对此的考虑是为什么任何人都喜欢在静态构造函数中执行它,如果给定类型在所有调用中都不正确,则只调用一次,而不仅仅是一次,我希望在使用错误类型的所有代码部分中得到异常。

这是我的意思的例子:

internal sealed class GenericTypeThatRequiresAnEnum<T> {
    static GenericTypeThatRequiresAnEnum() {
        if (!typeof(T).IsEnum) {
        throw new ArgumentException("T must be an enumerated type");
        }
    }
}

为什么不只是非静态构造函数?

4

1 回答 1

4

因为如果静态构造函数失败,您根本无法使用特定类型。因此,没有必要到处检查类型参数。

 public class Test<T>
    {
        static Test()
        {
            throw new InvalidOperationException();
        }
    }

用法:

new Test<string>(); //throws TypeInitializationException
于 2013-04-05T13:55:49.943 回答