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

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

问题描述

在C#中,下列类型推断如下:

 变种s =ABCD;

但为什么不能在类型推断当变量是一个常数?

下面抛出编译时异常:

 常量变种s =ABCD; //< =编译时错误:
                      //隐式类型的局部变量不能是常数


解决方案

  

实际上,我希望利珀特弹出通过与和的问题需要看看


如果有你想要的东西带到了我的注意,你可以在文本留下我的名字 - 没有评论 - 我最终会找到它。或者,更好的,你可以在推特,以 @ericlippert 。注意,这并不构成一个服务级别协议;我这样做在我的业余时间。


  

为什么不能类型推断当变量是一个常数?


不变与变是的对立面常量VAR 给我键入不寒而栗。常量是永远不会改变,并没有存储位置的值;一个变量是一个存储位置的内容改变。他们是完全不同的,所以不要试图把它们结合起来。之所以选择 VAR 语法来喊一声这是一个变量,我们正在与它坚持。

VAR 可以代表一个特定的类型声明,但它与组合常量严重muddies的画面是什么编译器的确实的与价值。因此,常量VAR 是不允许以prevent这种困惑,你必须明确地键入您的常量。

我将与推断常量完美的罚款不使用 VAR

 常量丕= 3.14159;

似乎没什么问题。不过,据我所知,没有计划把它添加到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

解决方案

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

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?

"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 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.

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

const Pi = 3.14159;

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

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

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