C# - 静态类型不能用作类型参数 [英] C# - static types cannot be used as type arguments
问题描述
我有一个通用类,它可以帮助我检查参数值
I've a generic class, that helps me to do checks on argument values
internal sealed class Argument<T>
where T : class
{
private void TraceAndThrow(Exception ex)
{
new InternalTraceHelper<T>().WriteError(ex);
throw ex;
}
internal void ThrowNull(object value, string argName)
{
if (ReferenceEquals(value, null))
{
TraceAndThrow(new ArgumentNullException(argName));
}
}
internal void ThrowIf(bool condition, string argName)
{
if (condition)
{
TraceAndThrow(new ArgumentException(null, argName));
}
}
internal void ThrowNotInEnum(Type enumType, object value)
{
if (!Enum.IsDefined(enumType, value))
{
TraceAndThrow(new ArgumentOutOfRangeException(Resources.ArgEnumIllegalVal.InvariantFormat(value)));
}
}
}
但是当我尝试将它与静态类一起使用时:
But when I try to use it with a static class :
internal static class Class1
{
private static Argument<Class1> _arg;
}
我收到此错误(在编译时):
I got this error (at compilation):
静态类型不能用作类型参数
static types cannot be used as type arguments
我做错了什么?
推荐答案
这是故意的.
静态类试图防止不当使用,因此在几乎所有情况下,您不能在通常需要类型的 实例 的情况下使用它们......并且包括类型参数.
Static classes try to prevent inappropriate use, so in almost all situations, you can't use them in situations where you'd normally want an instance of the type... and that includes type arguments.
参见部分 "静态类"C# 6 规范中的一部分,适用于您可以引用静态类类型的非常有限的一组情况.
See section "Static classes" of the C# 6 spec for the very limited set of situations in which you can refer to static class types.
这篇关于C# - 静态类型不能用作类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!