【发布时间】:2021-08-30 11:03:03
【问题描述】:
我得到了这个 C# 代码来生成 10 个随机坐标点。代码生成一个包含 10 个坐标的 ArrayList,打印对象,对它们进行排序,然后再次打印它们:
using System;
using System.Collections;
namespace Point
{
class Program
{
public class Point
{
public int x;
public int y;
public Point(int X, int Y)
{
x = X;
y = Y;
}
override public string ToString()
{
return y + "." + x;
}
}
public static void PrintValues(IEnumerable myList)
{
foreach (Object obj in myList)
Console.WriteLine("{0}", obj);
Console.WriteLine();
}
static void Main(string[] args)
{
ArrayList AL = new ArrayList();
Random R = new Random();
for(int i = 0; i< 10; i ++)
{
Point p = new Point(R.Next(50), R.Next(50));
AL.Add(p);
}
PrintValues(AL);
AL.Sort();
PrintValues(AL);
}
}
}
我的问题:
-
为什么即使我不使用
p.ToString(),也会自动调用Point类中的ToString()方法? -
在这种情况下如何比较积分?我需要将类型更改为 int 或 double 吗?
【问题讨论】:
-
ArrayList 仍然存在只是为了向后兼容 2005 年 .Net 2 引入的泛型之前的代码,旧项目设置列表 Visual Studio,以及与 PowerShell 集合的兼容性。不要在那些非常特殊的场景之外使用 ArrayList。