gpt4 book ai didi

c# - 如何使用反射将一种类型转换为另一种类型?

转载 作者:太空宇宙 更新时间:2023-11-03 20:35:05 25 4
gpt4 key购买 nike

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

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

更新

这里是一些示例源代码:

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);

最佳答案

也许 Automapper

例如:

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

关于c# - 如何使用反射将一种类型转换为另一种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5368200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com