简体   繁体   English

如何复制列表<mapelement>按价值而不是按参考?</mapelement>

[英]How to copy List<MapElement> by value and not by reference?

I'm attempting to copy a List<Windows.UI.Xaml.Controls.Maps.MapElement> but have so far only managed to copy the reference.我正在尝试复制 List<Windows.UI.Xaml.Controls.Maps.MapElement> 但到目前为止只能复制参考。 Can anyone offer a way to do this without creating the original MapIcon object again.任何人都可以提供一种方法来做到这一点,而无需再次创建原始 MapIcon object。

I now understand why the methods i've attempted don't work, but i can't find a way around it.我现在明白为什么我尝试过的方法不起作用,但我找不到解决方法。

public void MyTestFunction(BasicGeoposition nPosition) 
{

List<MapElement> MyLandmarks = new List<MapElement>();

Geopoint nPoint = new Geopoint(nPosition, AltitudeReferenceSystem.Ellipsoid);

var needleIcon = new MapIcon    //has base class MapElement
{
    Location = nPoint,                      
    NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 0.5),                    
    ZIndex = 0,                    
    Title = "Point 1"
};
            
MyLandmarks.Add(needleIcon);

// Copy Mylandmarks by value 
// Attempt 1 - copies reference
// copyOfMapElements = new List<MapElement>();
// copyOfMapElements = MyLandmarks;
//
// Attempt 2 - copies reference

copyOfMapElements = new List<MapElement>(MyLandmarks);
}

You can use LINQ to do that:您可以使用 LINQ 来做到这一点:

copyOfMapElements = MyLandmarks.Select(l => new MapIcon{ Location = l.Location,                      
    NormalizedAnchorPoint = l.NormalizedAnchorPoint,                    
    ZIndex = l.ZIndex,                    
    Title = l.Title }).ToList();

Update: The above solution assumes that all list elements of type MapIcon only, but if you need more generic solution to handle all MapElement derived types then you can used serialization or reflection.更新:上述解决方案假定所有列表元素类型为MapIcon ,但如果您需要更通用的解决方案来处理所有MapElement派生类型,则可以使用序列化或反射。 Check this answer for JSON serialization: https://stackoverflow.com/a/55831822/4518630检查 JSON 序列化的答案: https://stackoverflow.com/a/55831822/4518630

Simple answer with only MapIcon items in the list:列表中只有MapIcon项目的简单答案:

copyOfMapElements = MyLandmarks.ConvertAll(lm => new MapIcon {
    Location = lm.Location,
    NormalizedAnchorPoint = lm.NormalizedAnchorPoint,
    ZIndex = lm.ZIndex,
    Title = lm.Title
});

But since MapIcon is derived from MapElement class and MyLandmarks list holds MapElement and not MapIcon which has its own set of properties you cannot use the example above (kinda weird there's no ICloneable interface implemented for these classes), so I'd probably check for the type of the element and create new instance accordingly.但是由于MapIcon是从MapElement class 派生的,而 MyLandmarks 列表包含MapElement而不是MapIcon ,它有自己的一组属性,您不能使用上面的示例(有点奇怪,这些类没有实现ICloneable接口),所以我可能会检查元素的类型并相应地创建新实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM