C#泛型类继承特性的限制

C#泛型类继承特性的限制

泛型类声明不能直接或间接使用 System.Attribute 作为基类。

A generic class declaration shall not use System.Attribute as a direct or indirect base class.

  • 直接继承 System.Attribute
// Compiler Error CS0698: 
// A generic type cannot derive from 'System.Attribue' because it is an attribute class
public class B<TValue> : Attribute {}
  • 间接继承 System.Attribute
public class B : Attribute {}

// Compiler Error CS0698: 
// A generic type cannot derive from 'System.Attribue' because it is an attribute class
public class C<T> : B {}

官方C#语言存储库会议笔记如下:

尽管从理论上讲这是可行的,但由于大多数运行时版本中存在 bug,因此无法正确工作(从未经过实际测试)。

我们需要一种机制来理解它适用于哪些目标运行时。我们目前也在研究这一点,因为我们在许多方面都需要这样的机制。在那之前,我们无法采用它。

结论:如果能够使足够多的运行时版本支持它,这将是下一个主要 C# 版本的候选特性。

引用

  1. Why does C# forbid generic attribute types?
    https://stackoverflow.com/questions/294216/why-does-c-sharp-forbid-generic-attribute-types

  2. Generic Attributes
    https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-02-21.md#generic-attributes

声明

内容准确性: 我会尽力确保所分享信息的准确性和可靠性,但由于个人知识有限,难免会有疏漏或错误。如果您在阅读过程中发现任何问题,请不吝赐教,我将及时更正。

posted on 2025-02-18 13:05  wubing7755  阅读(13)  评论(0)    收藏  举报