将枚举对象转换为等效的枚举对象

时间:2020-04-08 22:21:56

标签: c# .net visual-studio reflection enums

您好,我正在使用反射将对象类型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中的值设置为第二枚举中的等效值(这就是为什么我使用反射)?

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您需要按值转换,则可以执行以下操作:

if (sourceType.IsEnum && targetType.IsEnum)
{
    destObject = (T)sourceObject;
    return;
}

或按名称:

if (sourceType.IsEnum && targetType.IsEnum)
{
    destObject = (T)Enum.Parse(typeof(T), sourceObject.ToString());
    return;
}