我的问题是关于使用 new
作为值类型(int
、bool
,...)
int i = new int();
在这种情况下,i
被初始化为零值。
我读到,将 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()
那么就不可能编写这样的代码。
请注意,对于 int
、long
等,以及几乎所有其他原始值类型(bool
除外),以及对于 >bool
有 new bool() == false
),您可以使用数字文字来初始化它们(0, 1, ...),但对于其他值类型,您可以' t。您必须使用静态值(然后以其他方式构建)或 new 运算符。例如日期时间
:-)
你不能写:
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 撰写)
DateTime dt = default(DateTime);
(请注意,您甚至可以编写 int x = default(int)
:-) )
关于c# - 在什么情况下您会使用 new 关键字初始化值类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28785974/