我想从另一个对象克隆/复制一个对象,这是一个Outlook.Namespace接口的实例。我研究了 ICloneable Interface 。有克隆/深度克隆解决方案来克隆/复制对象。它们对于已知所有属性的类很有用。但是,使用as Outlook.Namespace,我不知道属性()如何克隆它。
你能给我一些建议吗?非常感谢。
该代码用于获取Outlook中联系人的电子邮件地址。我想在第Outlook.NameSpace otl
行
private static string GetEmailAddress(Outlook.NameSpace otl, string email, string emailtype, ref int nCount)
{
string sEmailIn = email;
Recipient rcp = null;
try
{
rcp = otl.CreateRecipient(email);
rcp.Resolve();
if (rcp.Resolved)
{
AddressEntry address = rcp.AddressEntry;
ExchangeUser user = address.GetExchangeUser();
email = user.PrimarySmtpAddress;
if (address != null)
{
Marshal.ReleaseComObject(address);
}
if (user != null)
{
Marshal.ReleaseComObject(user);
}
++nCount;
}
}
catch (System.Exception ex)
{
ShoreTrace.TraceLn("Exception while converting email: " + sEmailIn);
ShoreTrace.TraceLn("Content " + ex);
ShoreTrace.TraceLn("Resulting email: " + email);
return sEmailIn;
}
finally
{
if (rcp != null)
{
Marshal.ReleaseComObject(rcp);
}
}
return email;
}
--------更新----------
我调试并观察otl对象的值,你可以看到下图。我想我们可以使用foreach循环来浏览它的所有属性。然后重新分配给相同类型的对象。请参阅下面的代码并提出您的意见
注意:请在新的水龙头中打开图片,以便更清楚地看到。
public static object Clone(object obj)
{
object new_obj = Activator.CreateInstance(obj.GetType());
foreach (PropertyInfo pi in obj.GetType().GetProperties())
{
if (pi.CanRead && pi.CanWrite && pi.PropertyType.IsSerializable)
{
pi.SetValue(new_obj, pi.GetValue(obj, null), null);
}
}
return new_obj;
}
答案 0 :(得分:0)
solution
下方generic
...但只有class
为serializable
/// <summary>
/// Only applicable for serializable object
/// Makes a copy from the object.
/// Doesn't copy the reference memory, only data.
/// </summary>
/// <typeparam name="T">Type of the return object.</typeparam>
/// <param name="item">Object to be copied.</param>
/// <returns>Returns the copied object.</returns>
public static T Clone<T>(this T item)
{
if (item != null)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, item);
stream.Seek(0, SeekOrigin.Begin);
T result = (T)formatter.Deserialize(stream);
stream.Close();
return result;
}
else
return default(T);
}