开发者

C# - static types cannot be used as type arguments

开发者 https://www.devze.com 2023-03-02 11:55 出处:网络
I\'ve a generic class that helps me to do checks on argument values: internal sealed class Argument<T>

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 ca开发者_如何转开发nnot be used as type arguments

What am I doing wrong?


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 "Static classes" of the C# 6 spec for the very limited set of situations in which you can refer to static class types.


Generics only work with instances, not static classes.


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


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


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 do this with extension methods instead of a generic class.

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

0

精彩评论

暂无评论...
验证码 换一张
取 消