为什么typeof(int).ToString()不是常数? [英] Why typeof(int).ToString() is not constant?

查看:115
本文介绍了为什么typeof(int).ToString()不是常数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这样做:

const string intType = typeof(int).ToString();
switch (typeof(MyT).ToString())
{
    case intType:
    {
        return "int";
        break;
    }
    ...
}

但是编译器说:


错误CS0133:分配给'intType'的表达式必须是常量

error CS0133: The expression being assigned to 'intType' must be constant

我知道, typeof 运算符在编译时起作用。那么,怎么了?

As I know, typeof operator works at compile-time. So, what's wrong?

推荐答案


据我所知,typeof运算符在编译时起作用。

As I know, typeof operator works at compile-time.

您不知道,因为知识必须是 true 。您从哪里得到在编译时执行 typeof 的想法?它产生一个非常数对象。而且不能保证 ToString 每次运行时都不会产生不同的字符串,因此也不能将其视为常量。

You don't know that because knowledge has to be true. Where did you get the idea that typeof is executed at compile time? It produces a non-constant object. And then there is no guarantee that ToString doesn't produce a different string every time it runs, so it cannot be treated as a constant either.


那么,怎么了?

So, what's wrong?

您是从错误中进行推理

C#规范清楚地描述了将表达式作为编译时常数必须满足的条件。这些条件包括不包含任何 typeof 运算符或方法调用的表达式。

The C# specification clearly describes the conditions that must be met for an expression to be a compile-time constant. Those conditions include the expression not containing any typeof operator or method call.

但是这里存在更大的问题。我假设 MyT 是通用类型参数,这意味着您正在尝试打开通用类型参数的值。

But there are far bigger problems here. I assume that MyT is a generic type parameter, which means you are attempting to switch on the value of a generic type parameter. That is almost always the wrong thing to do.

您真正想做的是什么?您到底要解决什么问题?因为到目前为止,您所显示的这段代码表明您正在走无用的道路来解决真正的问题。

What are you really trying to do? What problem are you really trying to solve? Because this code you've shown so far indicates that you're going down an unproductive path to solve whatever the real problem is.

这篇关于为什么typeof(int).ToString()不是常数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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