初始化.NET中的空变量 [英] Initializing null variables in .NET

查看:225
本文介绍了初始化.NET中的空变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是正确的方法来初始化.NET空变量?我已经告诉我的同事说,很难定义一个变量为null是放缓的。

What is the proper way to initialize a null variable in .NET? I've been told by one of my colleagues that hard defining of a variable to null is a slowdown.

int var1;          // good practice
string s1;         // good practice

int var2 = 0;      // bad practice
string s2 = null;  // bad practice

这是否正确?

Is that correct?

推荐答案

假设你实际上意味着的默认的值,而不是一个的的值,它可能慢下来非常,非常轻微的,如果你实际上是在构造函数中,而不是在变量声明赋值。如果它的变量声明我的也许的期望JIT编译器,以消除不必要的任务,作为对象的内存抹在第一次初始化的一部分。

Assuming you actually mean the default value instead of a null value, it could slow things down very, very slightly if you actually assign the value in the constructor instead of in the variable declaration. If it's part of the variable declaration I would probably expect the JIT compiler to remove the unnecessary assignment, as the object's memory is wiped on first initialization.

不过,这是显著的机会是在任何情况下绝对极小。

However, the chances of this being significant are absolutely tiny in either case.

哪个你觉得更可读的形式?这是的的更重要的案件占绝大多数。

Which do you find the more readable form? That's much more important in the vast majority of cases.

编辑:请注意,对于静态字段,至少有细微的情况下,这两个不行为相同的方式。这里有一个例子 - 在测试1和Test2的类不同的只有的中的声明是否具有分配方面:

Note that for static fields at least, there are subtle cases where the two don't behave the same way. Here's an example - the Test1 and Test2 classes differ only in terms of whether the y declaration has an assignment:

using System;

class Test1
{
    static int x = GetX();
    static int y = 0;

    public static void Hello()
    {
        Console.WriteLine("{0} {1}", x, y);
    }

    static int GetX()
    {
        y = 2;
        return 5;
    }
}

class Test2
{
    static int x = GetX();
    static int y;

    public static void Hello()
    {
        Console.WriteLine("{0} {1}", x, y);
    }

    static int GetX()
    {
        y = 2;
        return 5;
    }
}

class Test
{
    static void Main()
    {
        Test1.Hello();
        Test2.Hello(); 
    }
}

这篇关于初始化.NET中的空变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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