Search code examples
c#genericsinterface.net-assemblyactivator

How to cast implementation instance to interface without specifying generic argument (the implementation knows it)?


I have an interface:

public interface IA<T>
{
     T fce1(float[] data);
     byte[] fce2(T arg);        
}

and I have its implementation which specifies certain T (so the implementation do not need anything else):

public class A : IA<float>
{
   public float fce1(float[] data)
   {
       return 1f;//data processing
   }

   public byte[] fce2(float arg)
   {
       return BitConverter.GetBytes(arg);//some kind of serialization
   }        
}

Class A is in a.dll and I want to get it and call the fce2(fce1()) (so there should be no uknown argument or type. I want to do something following:

var data = File.ReadAllBytes("a.dll") 
var assembly = Assembly.Load(data);
var expTypes = assembly.GetExportedTypes();

foreach (var d in assembly.GetExportedTypes())
{
     var obj = Activator.CreateInstance(d);
     if (obj is IA)
     {
          var kernel = obj as IA;
          kernel.fce2(fce1());
     }
}

The purpose is to run fce1 as one Task later and fce2 as a second Task when fce1 provides result (this is simplyfied situation).

I tried this with .NET 4.7

I know it could be done to return the object from fce1 and then cast inside fce2 the object to desired type and process it? But is this the only way? I want to avoid casting.


Solution

  • Using the dynamic type, the methods invocation could be made (only the first call takes a long time, then it is quite efficient.

    float[] testingPacket = new float[6250000];
    dynamic instance = null;
    
    foreach (var d in assembly.GetExportedTypes())
    {
        instance = Activator.CreateInstance(d);
    }
    int L = 0;
    for (int i = 0; i < L; ++i)
    {
        dynamic result1 = instance.fce1(testingPacket);
        byte[] buffer = instance.fce2(result1) as byte[];
    }
    

    The higher the L is the duration period of the for cycle is closer to the duration of object casting and direct declaration using as IA. Thx.