我正在使用C#。尝试使用数组属性执行结构。这是我的代码:
namespace ConsoleApplication3
{
struct Dummy
{
public bool one;
public string two;
public int[] three;
public Dummy(bool o, string t, int[] th)
{
one = o; two=t; three=th;
}
}
class Program
{
static void Main(string[] args)
{
int[] K = {5,2};
Dummy d = new Dummy(true, "mnm", K);
Console.WriteLine("{0} {1} {2}", d.one, d.two, d.three);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
然而,d.three是System.Int32 []但不是{5,2}。我该如何解决?
答案 0 :(得分:1)
如果要打印数组,则需要枚举数组的每个元素
如果将它传递给需要像 Console.WriteLine 这样的字符串的函数,那么它会调用该数组上的ToString方法。
但是数组类没有实现ToString方法并调用基类 object.ToString()方法。最后一个方法只打印类的名称
相反,你可以使用枚举数组的 string.Join 并将结果连接成一个字符串:
Console.WriteLine("{0} {1} {2}", d.one, d.two,
"{" + string.Join(",", d.three) + "}");
答案 1 :(得分:0)
PrintArray(int [] array)。迭代每个元素并对其进行字符串化。
答案 2 :(得分:0)
因为Console.WriteLine
会为参数ToString()
调用int[]
对象上的d.three
,并且它会实际返回类型名称,因此您需要转换所有数组项都连接到一个串联字符串,您可以在这里使用String.Join
:
Console.WriteLine("{0} {1} {2}", d.one, d.two, String.Join(",",d.three));
现在这将给出预期的输出,这将是逗号分隔的数组项。