gpt4 book ai didi

c# - 在 C# 中克隆一个对象

转载 作者:太空狗 更新时间:2023-10-30 00:28:04 25 4
gpt4 key购买 nike

我想使用 ICloneable 接口(interface)克隆一个对象由于某种原因,我无法在我的程序中克隆。这是我的代码:

public class GeoInfo : ICloneable
{
private long InfoID;
private string InfoName;
private Location InfoLocation;
private string Description;
private InfoTypes InfoType;
public GeoInfo(long InfoID)
{

this.InfoID = InfoID;
}
public GeoInfo(long InfoID, Location InfoLocation):this(InfoID)
{
this.InfoLocation = InfoLocation;
}
public GeoInfo(long InfoID, string InfoName, Location InfoLocation, string Description, InfoTypes InfoType):this(InfoID,InfoLocation)
{
this.InfoName = InfoName;
this.Description = Description;
this.InfoType = InfoType;
}
public object ICloneable.Clone()
{
GeoInfo toReturn = new GeoInfo(InfoID, InfoName, InfoLocation, Description, InfoType);
return (object)toReturn;
}

当我尝试使用 Clone() 方法时,在另一个类中,由于某种原因编译器找不到该方法。这是我尝试克隆的另一种方法:

public InfoLayer(string LayerName,List<GeoInfo> oldGeoInfos)
{
this.LayerName = LayerName;
this.GeoInfos = new List<GeoInfo>();
oldGeoInfos.ForEach((item) =>
{
GeoInfos.Add((GeoInfo)((ICloneable)item.Clone()));
});
}

最佳答案

类型转换周围的括号不正确。应该是

GeoInfos.Add((GeoInfo)((ICloneable)item).Clone());

(顺便说一句:为什么是 .ForEach() ?

this.GeoInfos = oldGeoInfos.Select(item => ((GeoInfo)((ICloneable)item.Clone()))).ToList();

也做这项工作。)

关于c# - 在 C# 中克隆一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4119594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com