能否这样实现构造函数的重载

shijies 2020-10-03 09:49:35
设计了一个MyArray类,希望在输入不同的数组参数(一维数组、二维数组和交错数组)时,实现构造函数的重载,代码如下:

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

namespace ConsoleApp1
{
class MyArray
{
public int no;
public string[] numbers;
public string[,] names;
public string[][] scores;

public MyArray()
{
this.no = 0;
}
public MyArray(string[] numbers)
{
this.no = 1;
this.numbers = numbers;
}
public MyArray(string[,] names)
{
this.no = 2;
this.names = names;
}
public MyArray(string[][] scores)
{
this.no = 3;
this.scores = scores;
}

class Program
{
static void Main(string[] args)
{
string[] mf3 = { "c", "c++", "c#" };
MyArray myArray1 = new MyArray();
myArray1.no = 1;
myArray1.numbers = mf3;
Console.WriteLine("调用默认构造函数输出一维数组numbers");
foreach (string i in mf3) { System.Console.WriteLine(i); }

string[,] siblings = new string[,] { { "Mike", "Amy" }, { "Mary", "Albert" } };
MyArray myArray2 = new MyArray(string[,] siblings); //编译时这一句不能通过
Console.WriteLine("调用带参数的构造函数输出多维数组names");
foreach (string i in siblings) { Console.Write("{0} ", i); }
}
}
}
}


以上代码在编译时不能通过,请问何故?
...全文
460 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
threenewbee 2020-10-03
  • 打赏
  • 举报
回复
MyArray myArray2 = new MyArray(string[,] siblings); -> MyArray myArray2 = new MyArray(siblings);

110,571

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧