为什么 C# 禁止泛型属性类型? [英] Why does C# forbid generic attribute types?

查看:33
本文介绍了为什么 C# 禁止泛型属性类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这会导致编译时异常:

public sealed class ValidatesAttribute<T> : Attribute
{

}

[Validates<string>]
public static class StringValidation
{

}

我意识到 C# 不支持通用属性.然而,经过多次谷歌搜索,我似乎无法找到原因.

I realize C# does not support generic attributes. However, after much Googling, I can't seem to find the reason.

有谁知道为什么泛型类型不能从 Attribute 派生?有什么理论吗?

Does anyone know why generic types cannot derive from Attribute? Any theories?

推荐答案

好吧,我无法回答为什么它不可用,但我可以确认这不是 CLI 问题.CLI 规范没有提到它(据我所知),如果您直接使用 IL,您可以创建一个通用属性.C# 3 规范中禁止它的部分 - 第 10.1.4 节类基础规范"没有给出任何理由.

Well, I can't answer why it's not available, but I can confirm that it's not a CLI issue. The CLI spec doesn't mention it (as far as I can see) and if you use IL directly you can create a generic attribute. The part of the C# 3 spec that bans it - section 10.1.4 "Class base specification" doesn't give any justification.

带注释的 ECMA C# 2 规范也没有提供任何有用的信息,尽管它确实提供了一个不允许的示例.

The annotated ECMA C# 2 spec doesn't give any helpful information either, although it does provide an example of what's not allowed.

我的带注释的 C# 3 规范副本将于明天到达...我会看看是否能提供更多信息.无论如何,这绝对是语言决定而不是运行时决定.

My copy of the annotated C# 3 spec should arrive tomorrow... I'll see if that gives any more information. Anyway, it's definitely a language decision rather than a runtime one.

Eric Lippert 的回答(释义):没有特别的原因,除了避免语言和编译器的复杂性,用于不会增加太多价值的用例.

Answer from Eric Lippert (paraphrased): no particular reason, except to avoid complexity in both the language and compiler for a use case which doesn't add much value.

这篇关于为什么 C# 禁止泛型属性类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆