【问题标题】:Convert enum object to equivalent enum object将枚举对象转换为等效的枚举对象
【发布时间】:2020-04-08 22:21:56
【问题描述】:

您好,我正在使用反射将对象类型 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 中,以通用方式在第二个枚举中获取等效值(这就是我使用反射的原因)?

提前致谢!

【问题讨论】:

  • 出于好奇,为什么要经历这个麻烦呢?根据您的问题的一开始,需要一个类型 A2 来反映类型 A 的所有属性的需求是什么?为什么不能只使用 A 类型?另外,你找到this answer about converting between enums了吗?
  • 我认为枚举没有属性。枚举上的那些项目是字段。
  • Sean Skelly 我需要这样做,因为我正在为一个服务的包装器工作,该服务与三个不同的 web 服务一起使用,例如使用具有等效值的三个不同的枚举,因此,转换这三个不同的枚举到一个(反之亦然)我可以在某些条件下仅从一个包装器方法对三个服务中的所有方法进行所有调用......也许我认为这是错误的方式,但它可以工作,除了枚举......

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


【解决方案1】:

如果你需要按值转换,你可以这样做:

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

或按名称:

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

【讨论】:

    猜你喜欢
    • 2012-08-12
    • 2015-09-01
    • 2022-01-09
    • 1970-01-01
    • 2014-02-24
    • 2011-05-08
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多