jeudi 28 octobre 2021

Best way to convert from one type to another at runtime [closed]

EDIT: Similar questions have been asked before, but this question is unique because the class I want to convert/cast to is not known until runtime, which means I can't have the name of the class to be cast/converted into written in the code.

I haven't found a way to convert the following class to a generic type using reflection. Below would be an example of the class I would like to convert to the type below it without having a switch statement or pre-defined mappings.

DTOClass
{
   Id;
   ShortName;
   LongName;
   TableName; //TableName = "EmployeeType"
}

EmployeeType
{
   Id;
   ShortName;
   LongName;
   TableName;
}

An example of some code that I have tried is below.

    public void Update<T>(T dtoClass) where T : DTOClass
    {
        var ConvertedEntity =  MagicConversionMethod(entity.TableName,dtoClass);
        MyOrmService.Update(ConvertedEntity)
    }

Any help would be appreciated.





Aucun commentaire:

Enregistrer un commentaire