Understanding C#'s Limitation on Generic Attributes
C# prohibits the use of generic types as attributes. For example, the following code:
<code class="language-csharp">public sealed class ValidatesAttribute<T> : Attribute { } [Validates<string>] public static class StringValidation { }</code>
will fail to compile. While this restriction is well-known, the reasoning behind it is less clear.
The Common Language Infrastructure (CLI) specification doesn't explicitly forbid generic attributes. However, the C# 3 specification (section 10.1.4) clearly states the prohibition without justification. The ECMA C# 2 specification offers no further clarification.
Research indicates that the decision wasn't based on technical constraints, but rather a design choice. According to Eric Lippert (summarized), the complexity added by supporting generic attributes would outweigh the benefits, leading to a more complex language and compiler without providing substantial value to developers.
The above is the detailed content of Why Can't C# Have Generic Attributes?. For more information, please follow other related articles on the PHP Chinese website!