在 C# 中类型推断常量 [英] Type-inferring a constant in C#

查看:21
本文介绍了在 C# 中类型推断常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中,以下类型推断有效:

In C#, the following type-inference works:

var s = "abcd";

但是为什么当变量是常量时不能推断出类型呢?

But why can't the type be inferred when the variable is a constant?

以下会引发编译时异常:

The following throws a compile-time exception:

const var s = "abcd"; // <= Compile time error: 
                      //    Implicitly-typed local variables cannot be constant

推荐答案

我实际上希望 Lippert 出现并看看这个问题

I'm actually hoping Lippert pops by and and takes a look at the question

如果您想引起我的注意,您可以在文本中留下我的名字——而不是评论——我最终会找到的.或者,更好的是,您可以向 @ericlippert 发送推文".请注意,这并不构成服务水平协议;我在业余时间做这个.

If there's something you want brought to my attention, you can leave my name in the text -- not a comment -- and I'll find it eventually. Or, better, you can "tweet" to @ericlippert. Note that this does not constitute a service level agreement; I do this in my spare time.

为什么当变量是常量时不能推断类型?

why can't the type be inferred when the variable is a constant?

常数"和变量"是相反的.const var 让我不寒而栗.常量是一个永远不会改变并且没有存储位置的值;变量是内容发生变化的存储位置.它们是完全不同的,所以不要试图将它们结合起来.var 语法被选择用来表示这是一个变量",我们坚持使用它.

"constant" and "variable" are opposites. const var gives me the shudders to type. A constant is a value that never changes and has no storage location; a variable is a storage location whose contents change. They're completely different, so don't attempt to combine them. The var syntax was chosen to call out "this is a variable", and we're sticking with it.

var 可以代表特定的类型声明,但是将它与 const 结合使用会严重混淆编译器 的作用 与价值.因此,const var 是不允许的,以防止这种混淆,您必须明确键入常量.

var can stand in for a specific type declaration, but combining it with const severely muddies the picture of what the compiler does with the value. Therefore const var is disallowed to prevent this confusion and you have to explicitly type your constants.

对于不使用 var 的推断常量我会非常满意:

I would be perfectly fine with inferred constants that do not use var:

const Pi = 3.14159;

对我来说似乎很好.但是,我知道没有将它添加到 C# 的计划.

seems fine to me. However, I know of no plans to add this to C#.

这篇关于在 C# 中类型推断常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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