C# doesn't allow generic types as attribute base types. Attempting this, as shown below, results in a compile-time error:
<code class="language-csharp">public sealed class ValidatesAttribute<T> : Attribute { } [Validates<string>] public static class StringValidation { }</code>
This limitation, despite C#'s extensive generic support, is puzzling to many.
The CLI specification doesn't explicitly forbid generic attributes. However, direct IL examination shows their creation is possible. This points to the restriction originating within the C# language itself.
Neither the C# 3 specification (section 10.1.4) nor the ECMA C# 2 specification offers a clear explanation for this prohibition, despite documenting other attribute limitations.
Eric Lippert, a leading figure in the C# community, suggests the restriction simplifies both the language and its compiler. The perceived benefits of allowing generic attributes are deemed insignificant compared to the potential complexities they could introduce.
The above is the detailed content of Why Are Generic Types Not Allowed as Attribute Base Types in C#?. For more information, please follow other related articles on the PHP Chinese website!