.net - 哪种泛型参数约束组合将使 C# 编译器为 GenericParamConstraint 元数据表生成行?

标签 .net clr metadata cil

根据 CLR GenericParamConstraint 表的 Partition II 元数据规范,

The GenericParamConstraint table records the constraints for each generic parameter. Each generic parameter can be constrained to derive from zero or one class. Each generic parameter can be constrained to implement zero or more interfaces.

问题是我似乎无法找到正确的 C# 代码片段来让 C# 编译器在 GenericParamConstraint 表中生成一行。我尝试过使用

    public interface IFoo
    {
    }

    public interface IBaz
    {
    }

    public interface IBar
    {
    }
    public class Foo
    {

    }
    public class SampleClassWithGenericParamConstraint<T>
        where T : IFoo, IBaz, new()
    {
        public void DoSomething<U>(U arg1)
            where U : struct
        {
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
        }
    }

..但问题是 C# 编译器只为 GenericParam 表生成行,而不是为 GenericParamConstraint 表添加行。所以这是我的问题 - 是否有任何用 C# 编写的代码示例会强制 C# 编译器向 GenericParamConstraint 表添加元数据行,以便我可以使用示例二进制文件?如果这是 C# 编译器方面的某种限制,是否有等效的 ILASM 代码片段可以替代这项工作?

最佳答案

您一定很困惑,您发布的使用 csc 编译的确切代码会在 GenericParamConstraint 表中生成三行。

enter image description here

在此上下文中,GenericParam U 的标记为 2a000001,并且受 System.ValueType TypeRef 约束。 T (2a00000a) 受 IFoo 和 IBaz TypeDef 约束。

关于.net - 哪种泛型参数约束组合将使 C# 编译器为 GenericParamConstraint 元数据表生成行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5550538/

相关文章:

c# - 具有多个构造函数的记录类型

git - 将自定义元数据存储在 Git 存储库中的单个文件中

java - 网页中的可移动对象

r - 将包描述提取为 R 中的字符串

.net - WCF 与 Windows 服务中托管的 WCF 用于长时间运行的任务

c# - 使用 lambda 对多列进行分组

.net - 如何判断字节数组是否已被压缩?

c# - 带有可选参数的构造函数是否会重载它?

.net - 线程启动是否具有隐式内存屏障?

asp.net - 遍历 !DumpHeap 输出以读取内存偏移量处的值