c# - 在什么情况下您会使用 new 关键字初始化值类型?

标签 c# initialization value-type

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

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() 那么就不可能编写这样的代码。

请注意,对于 intlong 等,以及几乎所有其他原始值类型(bool 除外),以及对于 >boolnew 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/

相关文章:

c# - 在每个 SelectList 项上设置 Selected=True 不会影响呈现的 ListBox

c# - 如何将参数传递给批处理文件?

c - "int *p =0;"和 "int *p; *p=0;"有什么区别

c# - 在 Linq to Sql 查询中获取默认值类型 (DateTime),结果为空

.net-4.0 - 为什么我不能在 .NET 4.0 中将 List<int> 分配给 IEnumerable<object>

c# - 将值类型捕获到 lambda 时是否执行复制?

c# - WCF 数据限制

c# - 在 C# 中使用 streamReader 类读取具有动态列数的文本文件

c - 在 C 中初始化稀疏常量数组

c# - 为什么 C# 局部变量应该直接赋值,即使它是默认值?