gpt4 book ai didi

C# 帮助扩展方法 - 将集合转换为另一种类型

转载 作者:行者123 更新时间:2023-11-30 21:20:03 25 4
gpt4 key购买 nike

我想从

 public class Party
{
public string Type { get; set; }
public string Name { get; set; }
public string Status { get; set;}
}

并转换为

 public class Contact
{
public string Type { get; set; }
public string Name { get; set; }
public string Status { get; set;}
public string Company {get;set;}
public string Source {get;set;}
}

我试过使用这个扩展方法

   public static class EnumerableExtensions
{
public static IEnumerable<TTo> ConvertTo<TTo, TFrom>(this IEnumerable<TFrom> fromList)
{
return ConvertTo<TTo, TFrom>(fromList, TypeDescriptor.GetConverter(typeof(TFrom)));
}

public static IEnumerable<TTo> ConvertTo<TTo, TFrom>(this IEnumerable<TFrom> fromList, TypeConverter converter)
{
return fromList.Select(t => (TTo)converter.ConvertTo(t, typeof(TTo)));
}
}

我收到此错误 TypeConverter 无法将“Party”转换为“Contact”

    var parties = new List<Party>();
parties.Add(new Party { Name = "name 1", Status = "status 1" });
parties.Add(new Party { Name = "name 2", Status = "status 2" });

var results = parties.ConvertTo<Contact, Party>().ToList();

我在这里错过了什么?

最佳答案

Party 类型和 Type contact 之间没有直接转换(基于多态或继承)。

您需要为您的类型实现一个 TypeConverter,以便 .NET 知道如何在这两种类型之间进行转换:

MSDN - TypeConverter Class

MSDN - How to Implement a TypeConverter

创建 TypeConverter 后,您必须使用 TypeConverterAttribute 修饰两个类,以便框架可以在运行时获取 TypeConverter 的实例:

public class PartyTypeConverter : TypeConverter
{
// Implementation
}

[TypeConverter(typeof(PartyTypeConverter)]
public class Party
{
public string Type { get; set; }
public string Name { get; set; }
public string Status { get; set; }
}

您还可以尝试使用 LINQ 来模仿(我猜的)所需的行为(即使您会失去通用能力):

var contacts = parties.Select(p => new Contact {
Type = p.Type,
Name = p.Name,
Status = p.Status
});

关于C# 帮助扩展方法 - 将集合转换为另一种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3480313/

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