为什么类字段不能为var? [英] Why can't class fields be var?

查看:66
本文介绍了为什么类字段不能为var?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A
{
    A()
    {
        var x = 5;   // this is allowed
    }

    var _x = 5;   // the compiler is unhappy
}

我想编译器必须能够推断出成员变量的类型与本地变量的类型相同。那么有什么区别呢?

I guess the compiler must be able to deduce the type for the member variable just the same way it does it for the local one. So what's the difference?

推荐答案

Eric Lippert在这里回答了您的问题:> 为什么在字段上没有var?

Eric Lippert answered your question right here: Why no var on fields?

基本上,对于一般情况,它需要重写C#编译器,因为它当前执行类型推断的方式不适用于 var 字段变量分配的循环

Basically, for the general case it would require re-writing the C# compiler, as the way it currently does type inference would not work for cycles of var field variable assignments.

这篇关于为什么类字段不能为var?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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