且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

与结构初始化和默认参数直观行为

更新时间:2023-11-08 11:01:04

在C#(至少在C#6 - 的看博客帖子),调用新测试()等同于写默认情况下(测试) - 没有构造函数实际上是调用,提供了默认值

In C# (at least until C# 6 - see blog post), invoking new Test() is equivalent to writing default(Test) - no constructor is actually called, the default value is provided.

默认ARG也是没有用处的,什么情况是,它很可能会在编译和执行监督的结果,是由于这样的事实,可选参数是在C#4只加了:

The default arg serves no purpose, what happens is that it is likely the result of an oversight in the implementation of the compiler, due to the fact that optional arguments were only added in C# 4:


  • ,检查的可选参数不与现有的过载冲突的代码是不知道,在结构的情况下,初始化可能发生的冲突的;

  • 这是翻译什么的代码新测试()表示可能是不知道的可选参数的存在;

  • The code that checks that optional arguments do not conflict with already existing overloads is unaware of a possible conflict with the initializer in the case of structs;
  • The code that translates what new Test() means is probably unaware of the existence of optional arguments;

这是事实,编译器执行迄今最优化'新T()'基本上意味着默认(T)当T是一个结构。这实际上是一个错误 - 它总是应该调用实际参数的构造函数,如果有一个 - 这有可能是一直以来,因为它是允许在IL

It is true that the compiler implementation has so far "optimized" 'new T()' to mean essentially default(T) when T is a struct. That was actually a bug - it was always supposed to call an actual parameterless constructor if there is one - which there could have been all along, since it is allowed in IL.

有关你的榜样,这意味着新测试()由编译器有效地更换默认(测试) - 所以这是一个错误,将被固定在Visual Studio的下一个版本

For your example, it means that new Test() is effectively replaced by the compiler to default(Test) - so that is a bug, which will be fixed in the next version of Visual Studio.

在换句话说,你有一个极端例子。这很可能是看如何在Visual Studio中的下一个版本的行为,因为这种行为正在改变的好时机。

In other words, you have a corner case. That would probably be a good time to look at how that behaves in the next version of Visual Studio, as that behavior is changing.