gpt4 book ai didi

c# - 为什么不能将 Type 用作常量值?

转载 作者:可可西里 更新时间:2023-11-01 07:57:37 26 4
gpt4 key购买 nike

引用 MSDN - const (C# reference) :

A constant expression is an expression that can be fully evaluated at compile time. Therefore, the only possible values for constants of reference types are string and a null reference.

根据:typeof(T) vs. Object.GetType() performance , typeof(T) 是一个编译时表达式。

那么为什么 Type 不能是常量值呢?

以下代码不会编译:

public const Type INT_TYPE = typeof(int);

最佳答案

常量由编译器在生成的 IL 代码中替换为文字值。但是 typeof 是一个方法调用:

typeof(int);

// Becomes:
L_0000: ldtoken int32
L_0005: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)

关于c# - 为什么不能将 Type 用作常量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32212815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com