限制适用于隐式类型的变量声明 [英] Restrictions apply to implicitly-typed variable declarations

查看:41
本文介绍了限制适用于隐式类型的变量声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关

http://msdn.microsoft.com/en-us/library/bb384061.aspx

它规定了一个限制:

如果范围内名为var的类型,则var关键字将解析为该类型名称,并且不会被视为隐式类型的局部变量声明的一部分.

If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.

有人可以用C#示例解释语句的含义吗?

Can anybody explain what is mean by statement with C# example?

推荐答案

如果您这样做:

class var
{
    public static implicit operator var(int value)
    {
        return new var();
    }
}

var myVar = 5;

myVar 的类型为 var ,而不是 int 的类型.

The myVar will be of type var and not of type int.

(我添加的 operator 是为了使从 int 隐式转换为 var ).

(the operator I've added is so that there is an implicit conversion from int to var).

之所以插入此规则,是因为 var 不是C#中的保留关键字(并且仍然不是...如果您查看 var 的类/结构/枚举在C#2.0中有效.

This rule was inserted because var wasn't a reserved keyword in C# (and still isn't... If you look here you'll see it's a "contextual keyword"), so a class/struct/enum named var was valid in C# 2.0 .

  • 如果范围内有一个名为var的类型:如果范围内有一个名为var的类/结构/枚举(因此只需编写var就可以到达",而不必使用名称空间)

  • If a type named var is in scope: if there is a class/struct/enum named var that is in scope (so "reachable" by simply writing var, without having to use a namespace)

然后var关键字将解析为该类型名称:然后 var 表示您的用户定义类型"而不是关键字var"

then the var keyword will resolve to that type name: then var means "your user defined type" and not "the keyword var"

这篇关于限制适用于隐式类型的变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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