为什么我可以创建一个名为“var"的类? [英] Why can I create a class named "var"?

查看:35
本文介绍了为什么我可以创建一个名为“var"的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var 不是 C# 中的关键字吗?但是为什么我可以这样做:

Isn't var a keyword in C#? But why can I do this:

public class var { }

public class main
{
    public static void main(string[] args)
    {
        var testVar = new var();
    }
}

代码中使用的var是在main类之前声明的var类.编译器甚至没有抱怨.

The var that is used in the code is the var class that is declared before the main class. And the compiler doesn't even complain.

当我这样做时:

public class int { }

或者这个:

public class true { }

编译器说inttrue是关键字,不能这样使用.为什么和 var 不一样?

The compiler said that int or true is a keyword and cannot be used like that. Why is it not the same with var?

推荐答案

var 不是关键字 根据此列表.

它是一个上下文关键字,因此编译器可以根据上下文来决定哪个是您的类,哪个是上下文关键字,并且不会出现混淆.

it is a contextual keyword, so from the context the compiler is able to decide which is your class and which is the contextual keyword, and no confusion arises.

上下文关键字是:

用于在代码中提供特定含义,但它不是C#中的保留字.

used to provide a specific meaning in the code, but it is not a reserved word in C#.

因为它不是保留的所以你可以使用它.

so as its not reserved you can use it.

正如上面评论中指出的,在 Eric Lipperts 博客

As pointed out in the comments above there is a discussion of the differences as well as a list of the various keywords and contextual keywords added at each version of c# on Eric Lipperts blog

有趣的是,由于关键字集是在 C#1.0 中决定的,因此没有添加任何内容,以保持向后兼容性.

It is interesting to note that since the set of keywords were decided upon in C#1.0 there have been no additions, so as to preserve backwards compatibility.

这篇关于为什么我可以创建一个名为“var"的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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