【发布时间】:2016-06-10 15:04:01
【问题描述】:
我在我的项目中使用 GeoJSON.NET 库。在某些时候,我需要更新数据库中的功能。作为其中的一部分,我需要访问所述特征的坐标,以便将该信息也存储在数据库中。但是查看 GitHub 上的源代码,Feature 类具有 Geometry 属性作为 IGeometryObject:
public IGeometryObject Geometry { get; set; }
根据 GeoJSON 规范存在多种“形状”,例如“多边形”、“圆形”、“点”等。这些特定形状已在 GeoJSON.NET 项目中设置。
在这些具体类型中,我可以真正挖掘并访问各种坐标。
目前我有这个:
public int CreateFeature(Feature feature)
{
int featureId = 0;
var coordinatesDt = new DataTable();
coordinatesDt.Columns.Add("Latitude");
coordinatesDt.Columns.Add("Longitude");
//we are loading a datatable with the coordinates. This gets passed to a SQL server stored procedure as a single parameters to insert
//all the nodes.
LineString lineString = ((Polygon)feature.Geometry).Coordinates[0];
foreach (var coordinate in lineString.Coordinates)
{
var row = coordinatesDt.NewRow();
row["Latitude"] = ((GeographicPosition)coordinate).Latitude;
row["Longitude"] = ((GeographicPosition) coordinate).Longitude;
coordinatesDt.Rows.Add(row);
}
using (SqlConnection conn = new SqlConnection(_smmConnectionString))
using (SqlCommand cmd = new SqlCommand("dbo.MyProc", conn))
{
//set up params, set up TVP and execute...
}
return featureId;
}
这是 Polygon 类的一个 sn-p:
public List<LineString> Coordinates { get; set; }
因此,在我的代码中,我实际上是在对 Polygon 进行显式向下转换,因为我需要访问 Polygon 类的 Coordinates 成员。我知道我这样做是安全的,仅基于这些是我在我的应用程序中使用的唯一“类型”形状,即使我知道这不一定是最佳实践。但是,将来如果我们要使用其他类型,这将完全崩溃。我可以使用“is 或 as”来实现类型检查,但这仍然不能让我摆脱不得不向下转型的想法。
所以我的问题是最好的方法是什么?我已经阅读了有关为什么使用接口以及所有这些作为成员和/或参数的原因,并且必须进行明确的向下转换是“通常”不好的做法并且遵循不好的设计模式......除了极少数情况。那么我是属于“罕见情况”还是有更好的方法来解决这个问题?
【问题讨论】:
标签: c# .net interface casting geojson