为什么没有未分配的局部变量自动初始化? [英] Why aren't unassigned local variables automatically initialized?

查看:348
本文介绍了为什么没有未分配的局部变量自动初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好像是没有办法有未分配的局部变量在code或检查它们,因为编译器吐出使用未分配的局部变量错误

It seems like there is no way to have unassigned local variables in your code or check for them, as the compiler spits out Use of unassigned local variable error.

为什么编译器不使用默认(T)这些变量在编译时?

Why is the compiler not using default(T) on these variables at compile time?

即使它是很难做到的值类型,引用类型可以很容易地在这种情况下初始化为,对吧?

Even if it's harder to do for value types, references types could easily be initialized to null in this case, right?

下面是一些测试code:

Here is some test code:

public void Test ( )
{
    int x;
    string s;

    if ( x == 5 )
        Console.WriteLine ( 5 );

    if ( s != null )
        Console.WriteLine ( "s" );
}

返回:

Use of unassigned local variable 'x'
Use of unassigned local variable 's'

更新:

有关声称这是不允许的一个很好的理由谁的人,为什么会允许一个一流的水平?

For people who claims this is not allowed for a good reason, why is it allowed on a class level?

public class C
{
    public int X;
    public string S;

    public void Print ( )
    {
        Console.WriteLine ( X );
        Console.WriteLine ( S );
    }
}

这code编译完全没有问题。

This code compiles perfectly fine.

为什么罚款有一个一流的水平,但不是在方法级别?

Why is it fine to have on a class level but not on a method level?

推荐答案

C#是坑成功的语言。

C# is a "pit of success" language.

这是一个设计决策,因为语言是完全有能力让您的使用还没有明确分配了当地人。然而,这通常是真实的,这种变量的用法是错误的,那一个code路径没有设置某些原因的值。为了避免这样的错误,则编译器要求所有当地人在使用前进行分配。

This is a design decision, as the language is completely capable of allowing you to use locals that have not been explicitly assigned. However, it is normally true that usage of such variables is erroneous, that a code path has not set a value for some reason. To avoid such errors, the compiler requires that all locals be assigned before being used.

这篇关于为什么没有未分配的局部变量自动初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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