C# C扩展方法帮助-将集合转换为其他类型
我想转换成C# C扩展方法帮助-将集合转换为其他类型,c#,generics,extension-methods,type-conversion,C#,Generics,Extension Methods,Type Conversion,我想转换成 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
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”
这里缺少什么?在类型Party和类型contact-polymorphic或基于继承之间没有直接转换 您需要为您的类型实现类型转换器,以便.NET知道如何在这两种类型之间进行转换: 创建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
});
这是一种稍微不同的方法,尽管其核心仍然是简单地将成员值从一个对象复制到另一个对象 将此添加到联系人类
public static explicit operator Contact(Party p)
{
return new Contact
{
Type = p.Type,
Name = p.Name,
Status = p.Status
};
}
然后像这样转换:
List<Party> parties = new List<Party>();
parties.Add(new Party { Name = "Foo", Status = "Bar" });
parties.Select<Party, Contact>(p => (Contact)p)
您可能希望将最后一位包含在某个扩展方法中,但我看不出有什么意义…是的,LINQ方法将起作用。我想可能还有其他的方法,但不幸的是没有。您要么实现TypeConverter方法,要么使用LINQ。
List<Party> parties = new List<Party>();
parties.Add(new Party { Name = "Foo", Status = "Bar" });
parties.Select<Party, Contact>(p => (Contact)p)