在 C# 中使用 var 和 default 进行声明

发布于 2024-12-03 01:44:20 字数 1344 浏览 3 评论 0原文

最近我看到一个人大量使用 var 和 default 关键字来声明变量(以及每个声明),像这样:

var employee = default(Employee);   //Employee is a class
var errorInfo = default(ErrorInfo); //ErrorInfo is struct; Blank is default value
var salary = default(Double);
var isManager = default(Boolean?); 

而不是使用:

Employee employee = null;           //Employee is a class
ErrorInfo errorInfo = Blank;        //ErrorInfo is struct; Blank is default value
Double salary = 0.0;
Boolean? isManager = null;

或者,而不是使用 Even:

Employee employee;                  //Employee is a class
ErrorInfo errorInfo;                //ErrorInfo is struct; Blank is default value
Double salary;
Boolean? isManager;

现在使用 var 和 default for 每个变量的声明是我不习惯的。

想知道:
- 如果这是推荐的做法?
- 您的观点和偏好?

PS:
- 已完成在 C# 中使用 var 关键字在变量声明中使用“var”类型https://stackoverflow.com/questions/633474/c-do-you-use-var 然而,认为这个问题虽然相关但略有不同,因为它仅围绕声明/初始化而不是围绕赋值。
- 我理解片段 2 和片段 3 之间的区别。但是,问题更多地围绕片段 1。
- 如果你强烈认为这个问题属于stackexchange程序员,请随意移动。

Recently I saw a person heavily using var and default keywords for declaration of variables (and for every declaration), something like this:

var employee = default(Employee);   //Employee is a class
var errorInfo = default(ErrorInfo); //ErrorInfo is struct; Blank is default value
var salary = default(Double);
var isManager = default(Boolean?); 

instead of using:

Employee employee = null;           //Employee is a class
ErrorInfo errorInfo = Blank;        //ErrorInfo is struct; Blank is default value
Double salary = 0.0;
Boolean? isManager = null;

or, instead of using even:

Employee employee;                  //Employee is a class
ErrorInfo errorInfo;                //ErrorInfo is struct; Blank is default value
Double salary;
Boolean? isManager;

Now using var and default for declaration for every variable is something i am not accustomed to.

Want to know:
- If this is a recommended practice?
- Your views and preference?

PS:
- Have gone through Use of var keyword in C#, Use of "var" type in variable declaration and https://stackoverflow.com/questions/633474/c-do-you-use-var, however, think that this question although related is slightly different as it is solely around declaration/initialization and not around assignment.
- I understand the difference between snipped 2 and snippet 3. However, question is more around snippet 1.
- If you strongly feel that this question belongs to programmers stackexchange feel free to move.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

同展鸳鸯锦 2024-12-10 01:44:20

我不会说任何关于“var”的事情,过去已经有过关于此的评论和讨论(足够了;-)

关于“default()”,我不会使用它来初始化已知的 类型,但仅限于泛型。它允许您提供默认(返回)值或可用于比较,从而有助于透明地处理值类型或引用类型。

I'm not going to say anything about "var" there have been comments and discussions about this in the past (sufficiently so ;-)

Concerning "default()" I would not use this to initialize a known type, but rather only in generics. There it helps to transparently handle value types or reference types by allowing you to provide a default (return) value or can be used in comparisons.

倒数 2024-12-10 01:44:20

好吧,我认为 default 关键字不是最常用的关键字,而且在我看来,它在泛型方面最能达到其目的,如下所示:

public class Foo<T>{

    private T _instance;
    public Foo<T>(){
        _instance = default(T);
    }
}

为了获得 T 的新默认实例 。
确实没有理由像您帖子中的场景 1 那样使用它。

然而,使用 var 是一个不同的问题,许多人认为这是一个可读性问题。当我编写代码时,我默认使用 var ,只是因为我发现它更容易阅读:

var me = new Person();

就可读性而言,这样做似乎有点多余

Person me = new Person();

我推荐的另一种情况是 var 是如果某件事变化。考虑以下示例:

public decimal Calculate(decimal one, decimal two){
    return one + two;
}

以及代码中的其他位置:

decimal d = Calculate(1M, 2M);

如果出于某种原因将 Calculate 的返回类型更改为 double,则需要更改所有位置您强烈定义了该变量。

如果您这样做,

var d = Calculate(1M, 2M)

则不必担心这个问题。 Double/Decimal 示例有点简单,但就重构和连接类而言,我发现这非常有用。

Well, the default keyword isn't the most used keyword I think, and in my opinion it serves its purpose best in terms of Generics, like so:

public class Foo<T>{

    private T _instance;
    public Foo<T>(){
        _instance = default(T);
    }
}

in order to get a new default instance of T.
There are really no reasons to use it like scenario 1 in your post.

Using var however is a different question, and many view this as a matter of readability. I default to var when I write code simply because I find it easier to read:

var me = new Person();

It seems a bit redundant in terms of readability to do

Person me = new Person();

Another case I recommend var is if something changes. Consider the following example:

public decimal Calculate(decimal one, decimal two){
    return one + two;
}

And somewhere else in your code:

decimal d = Calculate(1M, 2M);

If you for some reason change the return type of Calculate to, say, double you need to change all the places where you strongly defined the variable.

If you instead do

var d = Calculate(1M, 2M)

you don't have to worry about this. The Double/Decimal example is a bit simple, but in terms of refactoring and interfacing out classes, I've found this very useful.

笙痞 2024-12-10 01:44:20

我认为这是不好的做法,它会阻止编译器(和第三方工具)捕获与初始化变量失败相关的错误。一般来说,我尝试使声明和赋值尽可能接近。为变量分配不打算使用的值可能会引入难以捕获的微妙错误。通常我会:

SomeType variable1; //want to store something that will be out of scope later
using(blah)
{
    //...
    variable1=blah;
}
//use variable1 here

或者立即分配所需的值:

SomeType variable2 = new SomeType();
//use variable2 immediately

或者(对我来说,现在更频繁地)

var variable2 = new SomeType();

分配空/占位符值主要是毫无意义的。

I think this is bad practice which will prevent the compiler (and 3rd party tools) from catching bugs related to failure to initialize a variable. Generally I try to keep declaration and assignment as close to each other as possible. Assigning values that aren't intended to be used to variables can potentially introduce subtle bugs that are difficult to catch. Normally I'd either:

SomeType variable1; //want to store something that will be out of scope later
using(blah)
{
    //...
    variable1=blah;
}
//use variable1 here

or assign required value immediately:

SomeType variable2 = new SomeType();
//use variable2 immediately

or (for me, more frequently nowdays)

var variable2 = new SomeType();

assigning null/placeholder values is mainly pointless.

分分钟 2024-12-10 01:44:20

我使用 var 进行赋值。但是我总是使用类来声明实例。我通常也会在当时实例化它们以避免意外的 NullReferenceExceptions

I use var for assignment. However I always declare instances using the class. I generally also instantiate them at the time to avoid unexpected NullReferenceExceptions

櫻之舞 2024-12-10 01:44:20

代码没问题。

只需确保您不会复制此技术来初始化 0 不是默认值或 标记 枚举的枚举。

[Flags]
public enum MyFlags
{
    Test = 1,
    Test2 = 2
}

MyFlags flags = default(MyFlags);
Console.WriteLine(flags); // oops

The code is ok.

Just make sure that you don't copy this technique to initialize enums where 0 is not default value or flagged enumerations.

[Flags]
public enum MyFlags
{
    Test = 1,
    Test2 = 2
}

MyFlags flags = default(MyFlags);
Console.WriteLine(flags); // oops
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文