0

I have a function of Generic Type, the signature is as follows:


private object ChunkToObject<TElementObj, TEnum>(Chunk outputChunk, byte[] _dto)
    where TElementObj: class, new()
    where TEnum:struct, Enum
{

}

And it could work properly when I specify correct TElementObj and TEnum in a line of code.

//example
var result=ChunkToObject<lineItem, lineItemEnum>(chunk, dtoBytearray);

But here comes another question: how do I turn it into a batch-capable function?

I'm trying to assign the TElementObj & TEnum pair into arrays but it doesn't seem to work.

What I have tried:

Create a function called DtoToObj:


private object DtoToObj<TObj>(byte[] _dto, Chunk[] outputChunks, Type[] elementClassArray, Type[] elementEnumArray, params Func<TObj,object>[] properties)
where TObj: class , new()
{
    if (outputChunks.Length != properties.Length || outputChunks.Length != elementClassArray.Length || properties.Length!=elementClassArray.Length)
        return null;
    var _result = new TObj();
    for (int i = 0; i < outputChunks.Length; i++)
    {
        var _prop = properties[i];
        var _partialResult = (elementEnumArray[i])ChunkToObject<elementClassArray[i],elementEnumArray[i]>(outputChunks[i],_dto);
    }

    return null;
}

and then call this DtoToObj function like this:

var result=DtoToObj<TypeOfClass>(_dto.Result,
    new[] { _api.Chunks[nameof(TElementObj1)], _api.Chunks[nameof(nameof(TElementObj2)] },
    new Type[]{typeof(TElementObj1), typeof(TElementObj2)},
    new Type[]{typeof(TEnum1), typeof(TEnum2)}, new {x=>x.ListObj1, x=>x.ListObj2});

but it gives me an error at this line:

var _partialResult = (elementEnumArray[i])ChunkToObject<elementClassArray[i],elementEnumArray[i]>(outputChunks[i],_dto);

error message: Cannot apply operator '<' to operands of type 'method group' and 'System.Type'

Can anyone could point out a way to do it correctly? Thanks!

  • You try to call a generic method where the generic type parameter come from a variable. In this case, you need to use reflection : https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method – vernou Nov 06 '22 at 14:43

0 Answers0