在哪种情况下,您会使用新关键字初始化值类型? [英] In which scenarios would you initialize a value type with a new keyword?

查看:88
本文介绍了在哪种情况下,您会使用新关键字初始化值类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于将new用作值类型(intbool,...)

My question is about using new for a value type (int, bool,...)

int i = new int();

在这种情况下,i的初始化值为零.

in this case i is initialized with a value zero.

我已经读到,将new与值类型一起使用不是一件好事,但是,不能动态分配内存(仅在堆栈上). 所以问题是为什么C#编译器制造商让我们这样做,在这种情况下这种方法很方便?

I have read that it's not a good thing to use new with the value types and does not, however, dynamically allocate memory(just on stack). So the questions is why the C# Compiler makers have let us to do so, in which situation this method comes handy?

推荐答案

我读到,将new与值类型一起使用不是一件好事,但是,它不能动态分配内存(仅在堆栈上).那么问题是,为什么C#编译器制造商允许我们这样做,在这种情况下这种方法很方便?

I have read that it's not a good thing to use new with the value types and does not, however, dynamically allocate memory(just on stack). So the questions is why the C# Compiler makers have let us to do so, in which situation this method comes handy?

至少有一个原因:

void MyFunc<T>() where T : new()
{
    T someValue = new T();
    // probably other code here :-)
}

致电

MyFunc<int>();

使用泛型,您必须能够使用new().如果某些值类型不具有new(),则不可能编写这样的代码.

With generics you must be able to use the new(). if some value types didn't have the new() then it would be impossible to write code like that.

请注意,对于intlong,...以及几乎所有其他原始值类型(bool除外,对于boolnew bool() == false),可以使用数字文字进行初始化它们(0、1,...),但是对于其他值类型则不能.您必须使用静态值(然后以其他方式构建)或new运算符.例如DateTime:-)

Note that for int, long, ... and nearly all the other primitive value types (except bool, and for bool there is the new bool() == false) you can use numeric literals to initialize them (0, 1, ...), but for other value types you can't. You have to use static values (that are then built in some other ways) or the new operator. For example DateTime :-)

你不能写:

DateTime dt = 0;

您必须写:

DateTime dt = DateTime.MinValue; // Where DateTime.MinValue is probably defined as new DateTime()

DateTime dt = new DateTime();

DateTime dt = new DateTime(2015, 02, 28);

或(由Henk Holterman撰写)

or (as written by Henk Holterman)

DateTime dt = default(DateTime);

(请注意,您甚至可以编写int x = default(int) :-))

(note that you can even write int x = default(int) :-) )

这篇关于在哪种情况下,您会使用新关键字初始化值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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