- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
不确定我的白话是否正确,请耐心等待。
我在插件中使用了一个公共(public)接口(interface),我希望实现此接口(interface)的类可以克隆,同时保持它们的声明类型和其中的所有属性。
我知道 ICloneable
并且我可以简单地将其实现到我的界面中,但我不想将实现该界面的要求传递给插件开发人员并希望自己控制它。
另外值得注意的是,它需要轻巧,不需要很深。除了实现我的插件接口(interface)外,我在设计时也不知道声明类型的任何内容,因此我需要将其转换为“未知”源类型。
public interface ImyInterface
{
int commonProp {get;set;}
}
// This class and the properties therein are not known at design time
public myObj : ImyInterface
{
int commonProp {get;set;}
int uncommonProp {get;set;}
}
然后我需要从我的应用程序中调用类似这样的东西:
// This is how I generally "activate my plugins"
ImyInterface obj = (ImyInterface)Activator.CreateInstance(type);
// Then elsewhere I need to clone its current state.
var ClonedObj = obj.clone();
我试过了 this ,但这需要我在设计时知道类型。
最佳答案
我推荐你使用DeepCloner ,可从 NuGet 获得。我认为这个库恰好实现了您所需要的,并且作为扩展方法。它也是开源的并托管在 GitHub 中,因此如果您想添加更多功能或只是想了解它的工作原理,您可以查看代码。
来自项目网站:
Also, there is no requirement to specify object type for cloning. Object can be casted to inteface or as an abstract object, you can clone array of ints as abstract Array or IEnumerable, even null can be cloned without any errors.
我做了这个示例来展示它是如何工作的:
一个接口(interface)和一个实现这个接口(interface)的类:
interface IPluginInterface { }
class Foo:IPluginInterface
{
public int SomeInt { get; set; }
public string SomeString { get; set; }
public Foo()
{
SomeInt = 42;
SomeString = "SomeString";
}
public override string ToString() => $"SomeInt: {SomeInt}. SomeString: {SomeString}";
}
然后在 main 中添加 using Force.DeepCloner; 和...
static void Main(string[] args)
{
IPluginInterface foo = new Foo();
IPluginInterface fooWithActivator = (IPluginInterface) Activator.CreateInstance(typeof(Foo));
Console.WriteLine(foo);
var cloneOfFoo = foo.DeepClone();
var cloneOfFooWithActivator = fooWithActivator.DeepClone();
Console.WriteLine(cloneOfFoo);
Console.WriteLine(cloneOfFoo == foo);
Console.WriteLine(cloneOfFoo.GetType());
Console.WriteLine(cloneOfFooWithActivator);
Console.WriteLine(cloneOfFooWithActivator == foo);
Console.WriteLine(cloneOfFooWithActivator.GetType());
Console.ReadLine();
}
输出:
EDIT>>>> 基于您对性能的担忧,我进行了一些测试,并找到了另一种更好的方法来实现您想要的。
更好的方法是调用 MemberwiseClone 方法,同时使用 Reflection、Delegates 和 Jon Skeet。这个想法是将 methodinfo 实例转换为委托(delegate),更多信息可以在 this 中找到。乔恩·斯基特 (Jon Skeet) 发表。
这是 main():
static void Main(string[] args)
{
const int howManyTimes = 10000000;
IPluginInterface foo = new Foo(true);
foo.ShallowCloneWithDeepClonerLibrary(howManyTimes);
foo.ShallowCloneWithReflection(howManyTimes);
((Foo)foo).ShallowCloneWithMemberWiseClone(howManyTimes);
foo.ShallowCloneWithDelegatesAndReflection(howManyTimes);
Console.ReadLine();
}
正如您可能注意到的,我们正在测试四种浅克隆方法:
这是所有 4 个方法的代码(它们是扩展方法):
public static void ShallowCloneWithDeepClonerLibrary(this object obj, int times)
{
Console.WriteLine($"Performing {times.ToString("##,###")} cloning operations with DeepCloner's ShallowClone method:");
var sw = new Stopwatch();
sw.Start();
for (var i = 0; i < times - 1; i++) obj.ShallowClone();
var clone = obj.ShallowClone();
sw.Stop();
Console.WriteLine($"Total milliseconds elapsed: {sw.ElapsedMilliseconds}");
Console.WriteLine($"Are both the same: {obj == clone}");
Console.WriteLine($"Cloned object: {Environment.NewLine}{clone}{Environment.NewLine}");
}
public static void ShallowCloneWithMemberWiseClone(this Foo obj, int times)
{
Console.WriteLine($"Performing {times.ToString("##,###")} cloning operations wiht MemberwiseClone:");
var sw = new Stopwatch();
sw.Start();
for (var i = 0; i < times - 1; i++) obj.Clone();
var clone = obj.Clone();
sw.Stop();
Console.WriteLine($"Total milliseconds: {sw.ElapsedMilliseconds}");
Console.WriteLine($"Are both the same: {obj == clone}");
Console.WriteLine($"Cloned object: {Environment.NewLine}{clone}{Environment.NewLine}");
}
public static void ShallowCloneWithDelegatesAndReflection(this object obj, int times)
{
Console.WriteLine(
$"Performing {times.ToString("##,###")} cloning operations by encapsulating MemberwiseClone method info in a delegate:");
var sw = new Stopwatch();
sw.Start();
var type = obj.GetType();
var clone = Activator.CreateInstance(type);
var memberWiseClone = type.GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic);
var memberWiseCloneDelegate =
(Func<object, object>)Delegate.CreateDelegate(typeof(Func<object, object>), memberWiseClone);
for (var i = 0; i < times; i++) clone = memberWiseCloneDelegate(obj);
sw.Stop();
Console.WriteLine($"Total milliseconds: {sw.ElapsedMilliseconds}");
Console.WriteLine($"Are both the same: {obj == clone}");
Console.WriteLine($"Cloned object: {Environment.NewLine}{clone}{Environment.NewLine}");
}
public static void ShallowCloneWithReflection(this object obj, int times)
{
Console.WriteLine($"Performing {times.ToString("##,###")} cloning operations manually with reflection and MemberwiseClone:");
var sw = new Stopwatch();
sw.Start();
var type = obj.GetType();
var memberWiseClone = type.GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic);
var clone = Activator.CreateInstance(type);
for (var i = 0; i < times - 1; i++)
clone = memberWiseClone.Invoke(obj, null);
sw.Stop();
Console.WriteLine($"Total milliseconds: {sw.ElapsedMilliseconds}{Environment.NewLine}");
Console.WriteLine($"Are both the same: {obj == clone}");
Console.WriteLine($"Cloned object: {Environment.NewLine}{clone}{Environment.NewLine}");
}
以及每次进行 10,000,000 次克隆操作的结果(以毫秒为单位):
所以,我们有一个赢家!不幸的是,获胜者不适合您的情况,因为这意味着在类里面公开 MemberwiseClone。但是......我们有一个巨大的第二名!
这是输出:
关于c# - 克隆一个对象,同时从扩展方法维护派生类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44847976/
我有 jquery Draggable/droppable 来处理包含和帮助器选项集。我想做的是将放置的项目的顶部和左侧参数存储在两个变量中。 我在下面的示例中实现了这一点(将新文档图标拖到框中),但
我有一个带有两个链接下拉列表的表单,我需要制作许多克隆,但保留链接。 这是一个示例,链接组合在我的应用程序中带有 json。 链式代码:
我在使用少量 jQuery 时遇到了一些逻辑问题。 我很确定我需要一个循环设置,但我很难将其组合在一起。我引用了 tuts、视频、工作示例、幻灯片,甚至是原始 javascript,但仍然难以将逻辑端
我有一个对象,它是一个基本的树。我需要对其进行深度复制,并发现自己实现了 __clone 方法。成功的代码是: function __clone() { $object = new Custo
我可以克隆一个没有内容的文本框吗?意味着如果我在克隆后在文本框中输入一些值,我想要一个空文本框。这可能吗?或者jquery克隆将其返回为innerHtml? 最佳答案 默认情况下,克隆会复制 的值目
我想复制或克隆我自己编写的类的对象。但如果我调用复制函数,则仅复制指针。因此,如果我更改复制的对象,原始对象也会更改。 有没有一种方法/功能可以真正克隆一个对象? 最诚挚的问候梅兰妮 最佳答案 如果一
我有一些 javascripc 代码: $(this).parent().siblings().find('.year-dropdown').find('.date, .time, .details'
我们有一个包含三个命名分支的存储库,我想克隆其中一个分支。有一个善变的命令可以做到这一点吗?如果我使用 hg clone 提供(分支)路径,则会收到 404 错误。 最佳答案 hg clone htt
我有带有 ObservableCollection 和其他属性的类。所以它看起来有点像这样: public class A { public int Id { get; set; } ..
我正在尝试下载一个大型开源项目的源代码,以便我可以查看它。 它说要做: hg clone http://server/path 但是,这需要很长时间(我假设是因为这是一个大项目)。我并不真正关心变更集
我发现这段代码随处可见,用于复制列表或克隆列表。 代码随处可见: clone([],[]). clone([H|T],[H|Z]):- clone(T,Z). ?-clone([1,2,3],Z).
我正在打印一个JFrame。在此之前,我隐藏菜单栏并将 JFrame 设置为未修饰。这工作得很好,但可见的 JFrame 发生了变化,以反射(reflect)我稍后必须恢复的已删除的控件。 我想克隆
我正在尝试复制一个 div 并将其附加到它的克隆之上。不幸的是,它似乎正在创建额外的重复项。这是怎么回事? 这是一个示例:http://jsfiddle.net/QEN5N/ 最佳答案 live 会将
为什么我不能克隆 ConcurrentHashMap ? ConcurrentHashMap test = new ConcurrentHashMap(); test.put("hello",
我有这个代码: openPopup.hide(); var substr = popupId.split('-'); var clone = $("#po
这段代码几乎可以正常工作假设我的表中有 10 行,我单击顶行,它会被克隆,然后添加到表的底部,而原始数据被删除,重复这些步骤 5 次。现在,我以克隆在底部的五行结束。 现在,如果我单击第一个克隆行,它
我已经设置了JSFiddle来展示我的问题。 我改变了克隆方式,使其更加通用,因此我不需要为不同的表重用代码。通常,对于 select2 元素,我会这样做 $(".campaignType", $tr
1 2 3 $('#things').after($('#things').clone()); 克隆时如何在这两个元素之间插入中断?有没有一种巧妙的方法可以用一行代码来完成
我正在从现有类型动态装配中创建新类型,但只包含选定的属性: public class EmitTest { public Type Create(Type prototype, Type dy
在我的游戏引擎中实现对象克隆的过程中,我遇到了一些绊脚石。我的目标是拥有一个克隆系统,我不必逐个类地维护它,除非该类需要特殊处理。 我的游戏引擎的设置围绕着一个基类 Object2D,它包含一些 Te
我是一名优秀的程序员,十分优秀!