C# - static types cannot be used as type arguments

2019-01-06 20:34发布

问题:

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

What I'm doing wrong?

回答1:

This is deliberate.

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.

See section 10.1.1.3.1 of the C# 4 spec for the very limited set of situations in which you can refer to static class types.



回答2:

Generics only work with instances, not static classes.



回答3:

Since static classes cannot be instantiated, it can never create Argument<T> with a static type.



回答4:

Since static classes won't have instance members, my concern would be what kind of thing I'm going to do with them.

I believe that, missing that you can't use static classes as generic arguments, I believe that you need to this with extension methods instead of a generic class.

  • http://msdn.microsoft.com/en-us/library/bb383977.aspx


回答5:

What you are doing wrong is using a static type as a generic type argument.