I am trying to implement an interface:
IListDto<TListDto>
And in my data repository, examine to see if a class implements that interface, and if so, call a
method defined by that interface. I am not having much success. The details are as follows...
Thanks in advance for any help you can provide.
// 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");
}
}
question from:
https://stackoverflow.com/questions/65877311/determine-if-a-class-implements-a-generic-interface-and-then-call-a-the-interfac 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…