尝试将坐标传递到多维数组时出现问题。抛出的错误:
(1)var newArray = item.To2dArray();在 GetInstructions() 方法中:
List 不包含 To2dArray 的定义,并且没有可扩展的方法 To2dArray 接受类型为 ist 的第一个参数
(2) 在添加public partial class SiteMaster : MasterPage方法时public static Coords[,] To2dArray(this List<List<Coords>> list)
扩展方法必须在非泛型静态类中定义
我的列表结构
public class Route
{
public string status_message { get; set; }
public string route_geometry { get; set; }
public int status { get; set; }
//route_instructions is what I'm interested in
public List<List<object>> route_instructions { get; set; }
}
public class Coords
{
public int Lat { get; set; }
public int Lon { get; set; }
public Coords(string a, string b)
{
this.Lat = Convert.ToInt32(a);
this.Lon = Convert.ToInt32(b);
}
}
List<Coords> Coordinates = new List<Coords>();
反序列化 JSON 的代码
private void GetInstructions()
{
string strurltest = String.Format("https://developers.onemap.sg/privateapi/routingsvc/route?start="+
startLat+","+ startLon +"&end="+ destinationLat +","+ destinationLon+"&"+
"routeType="+ transportType + "&token="+token);
WebRequest requestObjGet = WebRequest.Create(strurltest);
requestObjGet.Method = "GET";
HttpWebResponse responseObjGet = null;
responseObjGet = (HttpWebResponse)requestObjGet.GetResponse();
string strresulttest = null;
using (Stream stream = responseObjGet.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
strresulttest = sr.ReadToEnd();
sr.Close();
}
Route route = new JavaScriptSerializer().Deserialize<Route>(strresulttest);
route_geometry = route.route_geometry;
//display route instructions
foreach (var item in route.route_instructions)
{
var newArray = item.To2dArray();
System.Diagnostics.Debug.WriteLine(item[3]);
TextBox3.Text = TextBox3.Text + Environment.NewLine + item[9];
}
}
将列表对象转换为多维数组的代码
public static Coords[,] To2dArray(this List<List<Coords>> list)
{
if (list.Count == 0 || list[0].Count == 0)
throw new ArgumentException("The list must have non-zero dimensions.");
var result = new Coords[list.Count, list[0].Count];
for (int i = 0; i < list.Count; i++)
{
for (int j = 0; j < list[i].Count; j++)
{
if (list[i].Count != list[0].Count)
throw new InvalidOperationException("The list cannot contain elements (lists) of different sizes.");
result[i, j] = list[i][j];
}
}
return result;
}
打印时的列表对象采用以下格式:(System.Diagnostics.Debug.WriteLine(item[3]);在 GetInstructions() 中时)
1.315396,103.764419
1.314333,103.763455
1.312906,103.766496
1.312109,103.772234