2012-04-02 112 views
0

假设我有以下类型的代码:如何从现有实例创建相同类型的新实例?

foreach(var x in Mylist) //MyList is EntitySet 
{ 
//...... 
} 

我想知道x的类型,并创建另一个相同类型的新实例和克隆x到像新的实例:

foreach(var x in Mylist) 
{ 
    string tyoename = typeof(x).AssemblyQualifiedName; //get the type of x, but i got error here 
    //create instance of the type 
    //clone x data to new instance 
} 

MYLIST是动态数据,当Mylist改变时,x可能是不同的类型。 如何实现此请求?

+1

可能类似于这里的讨论有关克隆对象:http://stackoverflow.com/questions/78536/cloning-objects-in-c-sharp – 2012-04-02 20:04:14

+0

这是不可能在一般情况下,你将不得不对你想要克隆的对象做出一些假设......只要你认为你的对象是可序列化的,surfen的回答就非常好。 – Yaur 2012-04-02 21:06:08

回答

3

我用下面的扩展方法:

public static class CloningExtensions 
{ 
    public static T Clone<T>(this T source) 
    { 
//   var dcs = new DataContractSerializer(typeof(T), null, int.MaxValue, false, true, null); 
     var dcs = new System.Runtime.Serialization 
      .DataContractSerializer(typeof(T)); 
     using (var ms = new System.IO.MemoryStream()) 
     { 
      dcs.WriteObject(ms, source); 
      ms.Seek(0, System.IO.SeekOrigin.Begin); 
      return (T)dcs.ReadObject(ms); 
     } 
    } 
} 

像这样:

foreach(var x in Mylist) 
{ 
    var y = x.Clone(); 
} 

但是你必须小心使用类不支持序列化,因为此方法不调用构造函数并且不初始化私人领域。我用解决方法OnDeserializing/OnDeserialized方法(在每个类型,我需要能够克隆定义)

[OnDeserialized] 
private void OnDeserialized(StreamingContext c) 
{ 
    Init(); 
} 
0

,您可以创建动态像这样的类的对象了。

T ReturnObject<T>(T x) 
{ 
Type typeDynamic=x.GetType(); 
Type[] argTypes = new Type[] { }; 
ConstructorInfo cInfo = typeDynamic.GetConstructor(argTypes); 
T instacneOfClass = (T)cInfo.Invoke(null); 
return instacneOfClass; 
}