I am using a Record
as a DTO:
public record AccountTypeDTO(string Id, string Name):IEntityDTOBase;
IEntityDTOBase
is used only to access both properties Id
and Name
.
At this step I'm creating an instance in a generic method like that with reflection:
internal async IAsyncEnumerable<TEntityDTO> GetAsyncDTO<TEntityDTO>() where TEntityDTO:class,IEntityDTOBase
{
yield return (TEntityDTO)Activator.CreateInstance(typeof(TEntityDTO),Guid.NewGuid().ToString(),"thirdItem" ) ;
}
It works but I don't like.
Now I'm trying to follow this track:
internal async IAsyncEnumerable<TEntityDTO> GetAsyncDTO<TEntityDTO>() where TEntityDTO:class,IEntityDTOBase,new()
{
yield return new TEntityDTO() { Id = Guid.NewGuid().ToString(), Name = "thirdItem" };
}
new()
is mandatory to be able to create the instance in the generic method.- As I have the
new()
constraint, the caller of the method complainingmust be a non-abstract type with a public parameterless constructor, blà, blà, blà
- He also complains about
Id
andName
in the construction about readonly property
I can implement setters on AccountTypeDTO
and parameterless constructor to probably solve the issue but I'll loose the immuability and the benefit of a record, not an option.
Is there any other option to avoid reflection?
Aucun commentaire:
Enregistrer un commentaire