为什么不能将类型用作常量值? [英] Why can't a Type be used as a constant value?

查看:58
本文介绍了为什么不能将类型用作常量值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用 MSDN-const(C#参考):

常量表达式是可以在编译时完全求值的表达式.因此,引用类型常量的唯一可能的值为 string null 引用.

根据: typeof(T)与Object.GetType()性能 typeof(T)是一个编译时表达式.

According to: typeof(T) vs. Object.GetType() performance, typeof(T) is a compile time expression.

那么为什么 Type 不能为常数?

So why can't a Type be a constant value?

以下代码无法编译:

public const Type INT_TYPE = typeof(int);

推荐答案

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

Constants are substituted by the compiler with literal values in the resulting IL code. But typeof is a method call:

typeof(int);

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

这篇关于为什么不能将类型用作常量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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