[英]Determine if a class implements a generic interface and then call a the interfaces method
我正在尝试实现一个接口:
IListDto<TListDto>
在我的数据存储库中,检查 class 是否实现了该接口,如果是,则调用该接口定义的方法。 我没有太大的成功。 详细情况如下...
提前感谢您提供的任何帮助。
// I have a generic interface
public interface IListDto<TListDto>
{
TListDto ToListDto();
}
// This is an exaple of TListDto
public class ProductDto
{
public Guid ProductId { get; set; }
public string ProductName { get; set; }
}
// The product class implements IListDto<ProductDto>
public class Product : IListDto<ProductDto>
{
public Guid Id { get; set; }
public string ProductName { get; set; }
// ...other properties
// Implementation of IListDto<ProductDto>
public ProductDto ToListDto()
{
return new ProductDto()
{
ProductId = this.Id,
ProductName = this.ProductName
}
}
}
// I want to have a generic method in my Data Repository that can determine
// if a class implements TListDto. If it does, it converts the a list from
// List<TEntity> to List<TListDto> by calling the objects TListDto() implementation
public List<TListDto> ToDtoList(List<TEntity> list)
{
// The following is more or less pseudo-code as I am at a loss of where to take it from here...
// Test to see of TEntity implements IListDto
// ERROR 1: This test fails, even though TEntity implements IListDto
if (list is List<IListDto<TListDto>>)
{
// Yes, IListDto is implemented
// Cast list to List<IListDto>, the next line of code seems to work
List<IListDto<TListDto>> iList = list as List<TListDto>;
// ERROR 2: This line causes a nasty error message (System.NotSupportedException: Serialization
// and deserialization of 'System.Type' instances are not supported and should be avoided
/// since they can lead to security issues. Path: $.TargetSite.DeclaringType. etc...
var dtoList = iList.Select(s => s.ToListDto()).ToList();
return dtoList;
}
else
{
// No, throw not implemented error
throw new ApplicationException("Entity does not implement IListDto");
}
}
我几乎可以肯定你所遵循的方法不是最适合你试图解决的高级问题,所以如果你能准确解释这个问题是什么,我会很高兴,所以我可以给你更好的建议。
就是说,对您所问问题的回答是:
我想在我的数据存储库中有一个通用方法,可以确定 class 是否实现 TListDto。 如果是这样,它通过调用对象 TListDto() 实现将列表从 List 转换为 List
try {
var iList = list.Cast<IListDto<TListDto>>();
return iList.Select(s => s.ToListDto()).ToList();
} catch (InvalidCastException) {
throw new ApplicationException("Entity does not implement IListDto");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.