【发布时间】:2011-01-18 17:11:08
【问题描述】:
这里最简单的就是我想做的:
interface InterfaceA
{
string var1 { get; set; }
string var2 { get; set; }
}
public class DerivedA : InterfaceA
{
public string var1 { get; set; }
public string var2 { get; set; }
}
public class DerivedB : InterfaceA
{
public string var1 { get; set; }
public string var2 { get; set; }
}
public class DoEverything
{
InterfaceA A = new DerivedA();
InterfaceA B = new DerivedB();
A.var1 = "Test1";
A.var2 = "Test2";
B = ConvertObject<DerivedB>(A);
write(B.var1 + ", " + B.var2);
// This doesn't work, I would like it to though.
public T ConvertObject<T>(object obj)
{
T result = (T)typeof(T).GetConstructor(new Type[] { }).Invoke(new object[] { });
foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
if (propertyInfo.CanRead)
{
try
{
object value = propertyInfo.GetValue(obj, null);
propertyInfo.SetValue(result, value, null);
}
catch { }
}
}
return result;
}
}
现在我必须手动转换对象中的每个属性,当添加新属性时,我必须记住使用转换方法并添加它。我更希望这是自动完成的。
任何帮助将不胜感激。
提前致谢
【问题讨论】:
标签: c# derived-types