jeudi 14 avril 2016

How to use reflection to get implementations of a generic interface

I have a generic interface that requires a read and key method. I want to use reflection to get all implementations (each type) and store the key (as a key) and the type in a dictionary. Eventually I'd then have a method where I can look up a key in the dictionary and have it return an object of the correct type.

SO if I look up 61 in the dictionary, it will return to me an object of type IRead.

I hope this is understandable, if not I can answer questions in the comments.

This example only has int and string, but I'll have many more types in my real implementation.

public interface IRead<T>
{
    T Read(bool[] binary);
    int Key( T type );
}

public class Reader : IRead<int>, IRead<string>
{
    int IRead<int>.Read( byte[] binary )
    {
        // does stuff
        returns 4;
    }

    public int Key( int type ) { return 43; }

    string IRead<string>.Read( byte[] binary )
    {
        // does stuff
        returns "example";
    }

    public int Key( string type ) { return 61; }

    static StreamProcessor( )
    {
        // Here I want to get the definitions
    }
}





Aucun commentaire:

Enregistrer un commentaire