【问题标题】:How to convert one type to another using reflection?如何使用反射将一种类型转换为另一种类型?
【发布时间】:2011-03-20 11:31:15
【问题描述】:

我有两种非常相似的类型(即成员名称非常相似)。

有没有一种优雅的方法可以将一种类型复制到另一种类型,而不必手动复制每个单独的成员?

更新

这里是一些示例源代码:

main()
{
  FromCsvFile x = new FromCsvFile(fileName);
  OptionsEnt y = x.ToOptionsEnt(); // See helper function below.
}

// Chained helper function to convert type "FromCsvFile" to type "OptionsEnt".
// Want to replace this with something more elegant (perhaps with reflection?).
// Notice the corner cases, i.e. the "ExpirationDate" is a special conversion.
public static OptionsEnt ToOptionsEnt(this FromCsvFile fromCsvFile)
{
  return new OptionsEnt
           {
             Last = fromCsvFile.Last,
             Ask = fromCsvFile.Ask,
             Bid = fromCsvFile.Bid,
             Delta = fromCsvFile.Delta,
             EODsnapshotNewYorkTime = fromCsvFile.EODsnapshotNewYorkTime,
             Exchange = fromCsvFile.Exchange,
             ExpirationDate = fromCsvFile.Expiration.ToTypeIceDate(),
             Gamma = fromCsvFile.Gamma,
             IV = fromCsvFile.IV,
             LastDate = fromCsvFile.Date.ToTypeIceDate(),
             AdjustedStockClose = fromCsvFile.AdjustedStockClose,
             MeanPrice = fromCsvFile.MeanPrice,
             OptionType = fromCsvFile.OptionType == "C" ? OptionTypeEnum.enCall : OptionTypeEnum.enPut,
             OpenInterest = fromCsvFile.OpenInterest,
             Rho = fromCsvFile.Rho,
             StockSymbol = fromCsvFile.SymbolStock,
             StrikePrice = fromCsvFile.StrikePrice,
             Symbol = fromCsvFile.Symbol,
             StockPriceForIV = fromCsvFile.StockPriceForIV,
             Star = fromCsvFile.Star,
             Theta = fromCsvFile.Theta,
             Vega = fromCsvFile.Vega,
             Volume = fromCsvFile.Volume,
             IVnotInterpolated = fromCsvFile.IVnotInterpolated
          };
}

更新

决定使用 AutoMapper。

这里是替换上面代码的全部的代码(假设所有成员名称的名称和类型相同):

main()
{
  FromCsvFile x = new FromCsvFile(fileName);
  OptionsEnt y = Mapper.Map<FromCsvFile, OptionsEnt>(x);
}

由于我们需要一些自定义转换器(即 DateTime >> IceDateTime),这里是额外的代码行,其中包含参数“ExpirationDate”的自定义映射。添加此行可避免引发异常,因为它不知道如何将日期从一种格式转换为另一种格式。

 Mapper.CreateMap<DateTime, typeIceDate>().ConvertUsing(ConverterIceTypeIceDate.ToTypeIceDate);

【问题讨论】:

标签: c# .net visual-studio c#-4.0 .net-4.0


【解决方案1】:

也许是Automapper?

例如:

Mapper.CreateMap<FromCsvFile, OptionsEnt >();
return Mapper.Map<FromCsvFile, OptionsEnt>(fromCsvFile);

【讨论】:

  • 这听起来很棒。但是,它将如何处理极端情况? ExpirationDate 在一种类型中属于 DateTime 类型,在另一种类型中属于 IceDateTime 类型。在这些类型之间转换很容易 - 但我猜除非我告诉它“使用扩展方法将 IceDateTime 转换为 DateTime .ToDateTime”,否则映射将失败。
  • 啊哈!找到它:您可以添加自定义类型转换器,请参阅automapper.codeplex.com/…。
【解决方案2】:

为此使用AutoMapper 之类的东西。它将允许您简单地定义应该将类 OptionsEnt 映射到 FromCsvFile 并且如果它们具有具有相同名称和类型的属性,那么您将不需要定义任何其他内容。

否则您将不得不按属性进行迭代。

【讨论】:

  • 您提到“按属性迭代”我该怎么做?问题是存在一些极端情况,即 ExpirationDate 在一种类型中属于“DateTime”类型,在另一种类型中属于“IceDateTime”类型。
  • @Gravitas,您还将在 AutoMapper 中指定 IceDateTime 可以映射到常规 DateTime 并且 AM 将处理这两种类型的属性。
【解决方案3】:

见Copyable: A framework for copying or cloning .NET objects。它稍慢(它使用反射),但它有一个优点:您可以更改源以处理成员变量需要一些工作才能转换的极端情况。

例如,问题中的示例源码中,成员变量“ExpirationDate”在一种类型中是“DateTime”类型,在另一种类型中是“IceDateTime”类型(需要使用扩展方法转换日期格式.ToDateTime)。

这里是来源(更多来源请参见original blog entry):

// Modification to original source code.
Type type = instance.GetType();

if (instance.GetType().Name == "DataTable")
{
    // Added to handle custom type.
    DataTable dt = (DataTable)instance;
    copy = dt.Copy();
}
else if (instance.GetType().Name == "DataSet")
{
    // Added to handle custom type.
    DataSet ds = (DataSet)instance;
    copy = ds.Copy();
}
else
{
    // This is the original source.
    while (type != null)
    {
        foreach (FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
        {
            object value = field.GetValue(instance);
            if (visited.ContainsKey(value))
                field.SetValue(copy, visited[value]);
            else
                field.SetValue(copy, value.Clone(visited));
        }
        type = type.BaseType;
    }
}
return copy;

【讨论】:

  • 决定反对 Ox - 我真的不想更改映射器的核心源代码来添加我的自定义映射器。我正在使用 AutoMapper。
猜你喜欢
  • 2012-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-24
  • 1970-01-01
  • 1970-01-01
  • 2023-02-07
  • 1970-01-01
相关资源
最近更新 更多