Boo*_*mit 1 c# generics casting
我有几个对象具有相同的属性相应的对象.
class Source1
{
int id;
string name;
DateTime date;
}
class Destination1
{
int id;
string name;
DateTime date;
}
class Source2
{
int id;
string code;
double price;
}
class Destination2
{
int id;
string code;
double price;
}
Run Code Online (Sandbox Code Playgroud)
现在我想创建一个泛型类型的方法,可以将对象强制转换为相应的对象.
public TDestination Cast<TSource, TDestination>(TSource source)
{
//TDestination destination = (TDestination) source;
return destination;
}
Run Code Online (Sandbox Code Playgroud)
这里你最好的选择是引入一个通用接口(或基类).没有其他方法可以将项目转换为另一种项目.
public interface IItem
{
int id {get;set;}
string name {get;set;}
DateTime date {get;set;}
}
class Source1 : IItem
{
public int id {get;set;}
public string name {get;set;}
public DateTime date {get;set;}
}
class Destination1 : IItem
{
public int id {get;set;}
public string name {get;set;}
public DateTime date {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以将对象强制转换为界面并访问属性.
var item1 = (IItem)sourceItem;
var item2 = (IItem)destinationItem;
Run Code Online (Sandbox Code Playgroud)
如果您不想这样做,另一个选择是使用反射来源于源中的属性并创建目标类型的新对象并尝试使用共享名称映射属性.然而,这将创建一个新对象,并且与铸造完全不同.AutoMapper等库可以帮助您解决这个问题.
AutoMapper.Mapper.CreateMap<Source1, Destination1>();
var destItem = AutoMapper.Mapper.Map<Destination1 >(sourceItem);
Run Code Online (Sandbox Code Playgroud)