草庐IT

ICloneable

全部标签

c# - 将 .NET 库移植到 PCL 时如何解决缺少 ICloneable 接口(interface)的问题?

我正在将现有的.NET类库移植到可移植类库。.NET库广泛使用ICloneable接口(interface),不包括在可移植子集中。通常,我在.NET类库中遇到这样的类定义:publicclassFoowhereT:ICloneable{publicvoidBar(Titem){varx=item.Clone();...}}如何才能将此代码成功移植到可移植类库?我是否必须重写Clone方法调用,还是有侵入性较小的解决方法?我不能简单地删除通用类型约束whereT:ICloneable因为那时Bar方法将无法编译。我可以写一个替换接口(interface)来代替ICloneable在移植

C# 编译器错误?为什么这个隐式的用户定义转换不能编译?

给定以下结构:publicstructFoo{publicFoo(Tobj){}publicstaticimplicitoperatorFoo(Tinput){returnnewFoo(input);}}此代码编译:privateFooMakeFoo(){stringc="hello";returnc;//Success:stringisICloneable,ICloneableimplicitlyconvertedtoFoo}但这段代码无法编译——为什么?privateFooMakeFoo(){ICloneablec="hello";returnc;//Error:ICloneabl

C# 编译器错误?为什么这个隐式的用户定义转换不能编译?

给定以下结构:publicstructFoo{publicFoo(Tobj){}publicstaticimplicitoperatorFoo(Tinput){returnnewFoo(input);}}此代码编译:privateFooMakeFoo(){stringc="hello";returnc;//Success:stringisICloneable,ICloneableimplicitlyconvertedtoFoo}但这段代码无法编译——为什么?privateFooMakeFoo(){ICloneablec="hello";returnc;//Error:ICloneabl

c# - 如何在 C# 中克隆通用列表?

我在C#中有一个通用的对象列表,并希望克隆该列表。列表中的项目是可克隆的,但似乎没有执行list.Clone()的选项。有没有简单的方法解决这个问题? 最佳答案 如果你的元素是值类型,那么你可以这样做:ListnewList=newList(oldList);但是,如果它们是引用类型并且您想要深拷贝(假设您的元素正确实现了ICloneable),您可以这样做:ListoldList=newList();ListnewList=newList(oldList.Count);oldList.ForEach((item)=>{newLis

c# - 如何在 C# 中克隆通用列表?

我在C#中有一个通用的对象列表,并希望克隆该列表。列表中的项目是可克隆的,但似乎没有执行list.Clone()的选项。有没有简单的方法解决这个问题? 最佳答案 如果你的元素是值类型,那么你可以这样做:ListnewList=newList(oldList);但是,如果它们是引用类型并且您想要深拷贝(假设您的元素正确实现了ICloneable),您可以这样做:ListoldList=newList();ListnewList=newList(oldList.Count);oldList.ForEach((item)=>{newLis

c# - 实现 ICloneable 的正确方法

在类层次结构中实现ICloneable的正确方法是什么?假设我有一个抽象类DrawingObject。另一个抽象类RectangularObject继承自DrawingObject。然后还有多个具体类,如Shape、Text、Circle等,它们都继承自RectangularObject。我想在DrawingObject上实现ICloneable,然后将其向下传递到层次结构中,复制每个级别的可用属性并在下一级调用父级的Clone.但问题是,由于前两个类是抽象的,我无法在Clone()方法中创建它们的对象。因此,我必须在每个具体类中复制属性复制过程。或者有更好的方法吗?

c# - 为什么要在 C# 中实现 ICloneable?

你能给我解释一下为什么我要继承ICloneable并实现Clone()方法吗?如果我想做一个深拷贝,难道我不能只实现我的方法吗?让我们说MyClone()?为什么要继承ICloneable?有什么好处?仅仅是让代码“更具可读性”的问题吗? 最佳答案 你不应该。Microsoft建议不要实现ICloneable,因为界面上没有明确指示您的Clone方法是执行“深”克隆还是“浅”克隆。参见thisblogpostfromBradAbrams回到2003(!)了解更多信息。 关于c#-为什么要

c# - 为什么没有 ICloneable<T>?

通用ICloneable是否有特殊原因?不存在?如果我不需要在每次克隆某些东西时都施放它,那会舒服得多。 最佳答案 除了Andrey的回复(我同意,+1)-当ICloneable已完成,您也可以选择显式实现公开Clone()返回类型对象:publicFooClone(){/*yourcode*/}objectICloneable.Clone(){returnClone();}当然,通用ICloneable还有第二个问题-继承。如果我有:publicclassFoo{}publicclassBar:Foo{}我实现了ICloneabl