gpt4 book ai didi

c# - 将 NULL 传递给构造函数

转载 作者:IT王子 更新时间:2023-10-29 03:45:17 25 4
gpt4 key购买 nike

我不明白为什么构造函数是用参数Double[]执行的?

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyConsoleApp
{
class Program
{
static void Main(string[] args)
{
D myD = new D(null);
Console.ReadLine();
}

}

public class D
{
public D(object o)
{
Console.WriteLine("Object");
}
public D(double[] array)
{
Console.WriteLine("Array");
}
public D(int i)
{
Console.WriteLine("Int");
}
}
}

我想是因为第一个构造函数接受了一个引用类型的参数。第一个带有引用参数的构造函数,因为 null 是引用类型的默认值。

但是我不明白为什么不是object,它也是一个引用类型。

最佳答案

But I can not understand why no object? It's also a reference type?

是的,double[]object 都是引用类型,所以null 可以隐式转换为它们。但是,成员重载通常偏爱更具体的类型,因此使用了 double[] 构造函数。有关更多详细信息,请参阅 C# 规范的第 7.5.3 节(而且那里有很多详细信息)。

特别是从第 7.5.3.5 节开始:

Given two different types T1 and T2, T1 is a better conversion target than T2 if at least one of the following holds:

  • An implicit conversion from T1 to T2 exists, and no implicit conversion from T2 to T1 exists

这里就是这种情况,其中 T1double[]T2object。存在从double[]object的隐式转换,但没有从objectdouble[]的隐式转换,所以 double[] 是比 object 更好的转换目标。

如果你想强制使用 object 构造函数,只需转换:

D myD = new D((object) null);

关于c# - 将 NULL 传递给构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21664856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com