您好,我正在使用反射将对象类型A转换为等效的对象类型A2,这两种类型具有相同的属性和属性,对于此转换,我正在使用此常规程序:
public static void CopyObject<T>(object sourceObject, ref T destObject)
{
// If either the source, or destination is null, return
if (sourceObject == null || destObject == null)
return;
// Get the type of each object
Type sourceType = sourceObject.GetType();
Type targetType = destObject.GetType();
// Loop through the source properties
foreach (PropertyInfo p in sourceType.GetProperties())
{
// Get the matching property in the destination object
PropertyInfo targetObj = targetType.GetProperty(p.Name);
// If there is none, skip
if (targetObj == null)
{
// targetObj = Activator.CreateInstance(targetType);
continue;
}
// Set the value in the destination
targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);
}
}
这对于具有相同属性名称的简单对象非常有用,但是问题是当soruce和taget对象为任何ENUM类型时。
这行:
foreach (PropertyInfo p in sourceType.GetProperties())
不返回PropertyInfo对象,因此循环不会运行并且不会进行更改,因此没有错误,只是无法正常工作。
因此,无论如何使用反射将枚举类型A的一个对象转换为枚举类型A1的对象 我知道是没有任何意义的,但是我需要这样做才能使我的代码适应并存在于我没有源代码的应用程序中。
这个想法是:
有两个枚举
public enum A
{
vallue1=0,
value2=1,
value3=2
}
public enum A1
{
vallue1=0,
value2=1,
value3=2
}
以及那些枚举类型的两个对象:
A prop1 {get;set;}
A1 prop2 {get;set;}
我需要两个以常规方式获取prop1的枚举值,并在prop2中将该值设置为第二枚举中的等效值(这就是为什么我使用反射)?
提前致谢!