我正在研究用c#克隆对象的不同方法,但是目前我坚持使用简单的方法。我有一个带有静态变量的静态类,我想对我的一个静态变量进行精确复制。我在下面绘制了我的代码结构:
public static class RULE_SET
{
public static bool IsdataValid;
public static GCBRequest GCBData;
public static T Clone<T>(this T source)
{
try
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
catch (Exception ee) { return default(T); }
}
}
[XmlRoot(ElementName = "GCBRequest")]
public class GCBRequest
{
[XmlElement(ElementName = "PID")]
public string PID { get; set; }
[XmlElement(ElementName = "AID")]
public string AID { get; set; }
[XmlElement(ElementName = "CID")]
public string CID { get; set; }
}
//代码以加载RULE_SET
string strJsonRuleset = "{\r\n \"GCdBINRequest\": {\r\n\"PID\": \"(?s).*#M#20\",\r\n\"AID\": \"(?s).*#O#10\",\r\n\"CID\": \"(?s).*#O#25\"\r\n }\r\n}";
public class RULE_SET_LOCAL
{
public static GCBRequest GCBData;
}
//from other method
RULE_SET_LOCAL objParentRuleSet = new RULE_SET_LOCAL();
objParentRuleSet = JsonConvert.DeserializeObject<RULE_SET_LOCAL>(strJsonRuleset);
RULE_SET.GCBData = objParentRuleSet.GCBData;
// Main方法,我必须从中创建一个克隆对象
Object objRuleset;
objRuleset = RULE_SET.GCBData.Clone();
if(objRuleset == null)
{
** stuck here**
I don't know why Everytime I got the null object ?
}
// but I have use
objRuleset = RULE_SET.GCBData;
if(objRuleset != null)
{
** Successfully reached **
//But I can't do any operation on this object as it will effect the original one.
}
伙计们,您有解决方案/建议吗? 请帮助我理解这一点,将不胜感激。
谢谢。
答案 0 :(得分:0)
经过大量搜索后,我得到了这种方法:
public static T Clone<T>(this T source)
{
var serialized = JsonConvert.SerializeObject(source);
return JsonConvert.DeserializeObject<T>(serialized);
}
&现在我可以通过调用获取克隆了
object objRuleset = RULE_SET.Clone<GCBRequest>(RULE_SET.GCBData);