为什么C#不允许在泛型类内使用泛型类型作为属性?

11

这不是一个非常重要的问题,我只是好奇为什么不允许。错误信息并没有很好地解释,因为显然 "Att" 确实从 "Attribute" 继承。

public class Generic<Att> where Att : System.Attribute
{
    [Att] //Error: 'Att' is not an attribute class
    public float number;
}

1
不是完整的答案,但你可以这样做:Generic<OnlyAllowedOnMethodsAttribute> - bommelding
2
属性必须在编译时可解析。 - Alex K.
1
@AlexK。[MyAttribute<int>][MyAttribute(typeof(int))]一样可以在编译时解决。另一个问题是是否真的值得实现这个语法糖。 - InBetween
1个回答

2

属性必须仅在编译时定义,因为它存储在dll或exe中。并且只能包含编译时创建的信息。因此,出于这个原因,它不能是通用的。

编译器通常使用属性类型或其值,因此您无法稍后定义它。

在您的示例中,您想使用通用参数标记字段:

public class Generic<Att> where Att : System.Attribute
{
    [Att] //Error: 'Att' is not an attribute class
    public float number;
}

但是它等价于:

public class Generic<Att> where Att : System.Attribute
{
    [Attribute]
    public float number;
}

因为将来无法替换Att,所以没有理由在属性中使用泛型。

6
但是泛型类型本身就是一个编译时类型。 - MakePeaceGreatAgain
@HimBromBeere 所以,你会在二进制 DLL 中存储什么?只有“Att”类型吗?您无法在稍后覆盖它。没有理由通过通用方式声明它。 - Backs
2
[MyAttribute<int>] 而不是 [MyAttribute(typeof(int))] 是一个明显的使用案例,这可以改善(在某种程度上)语法。实际上,一些来源将此功能列为 C# 8 中的可能性:C# 8.0 - 新计划功能 - InBetween

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接