如何将匿名类型T转换为强类型类
我有这个类有两个参数作为匿名类型T.该方法应该有时采取任何类型的参数。
我尝试过使用var rest = pointOfSalesList.ChangeType(model, typeof(List<PointOfSaleModel>));
没有收到错误,但变量pointOfSalesList
未转换为强类型List<PointOfSaleModel>
。
internal override void Load<T>(T data, List<T> model)
{
// this does't work
var pointOfSalesList = Convert.ChangeType(model, typeof(List<PointOfSaleModel>));
}
我想将List<T> model
参数转换为强类型
internal class PointOfSaleModel : IPointOfSaleModel
{
public Guid PointOfSaleProviderUniqueId { get; set; }
public string CorporateId { get; set; }
public string Name { get; set; }
public string Adress { get; set; }
public int? ZipCode { get; set; }
public string Phone { get; set; }
public string ContactPerson { get; set; }
public string Email { get; set; }
public bool Status { get; set; }
}
我一直在努力解决这个问题。
答案 0 :(得分:0)
为什么不是这样的?
internal override void Load<T>(T data, List<T> model)
{
if (data.GetType() == typeof(PointOfSaleModel))
{
var pointOfSalesList = model as List<PointOfSaleModel>;
}
}
答案 1 :(得分:0)
此代码显示了没有任何技巧的强制转换但强制执行泛型(注意T:PointOfSaleModel)
class Caster
{
internal void Load<T>(List<T> model)
where T:PointOfSaleModel
{
// this should work
var pointOfSalesList = new List<PointOfSaleModel>(model);
}
}
class MainClass
{
public static void Main (string[] args)
{
var list = new List<PointOfSaleModel> {
new PointOfSaleModel{
Name = "name 1"
}
};
var caster = new Caster ();
caster.Load (list);
}
}