- 我有一个通用接口,需要读取和密钥方法。我想使用反射来获取每个实现的实例。
- 一旦我有了一个实现,我想知道它的关键,并将密钥和实例存储在字典中。
- 最后,我将有一个方法,我传递一个密钥和字节[],它会查找字典中的关键字,并使用它检索的实例读取字节[]并返回
object
。 - 我希望这是可以理解的,如果不是,我可以在评论中回答问题。
- 这个例子只有int和string,但是在我真正的实现中我会有更多的类型。
要与存储为例如2个项目的字典:
- 43,
IRead<int> new Reader()
- 61,
IRead<string> new Reader()
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
}
}
你不能根据接口'IRead'判断一个实现将有一个无参数的构造函数。那么你怎么知道你可以创建你发现的每种类型的实例呢? –
@ScottHannen我只是想将读者转换成字典中定义的类型 – JacobVoller
看起来您正在寻找某种IoC容器实现。看看[这](http://stackoverflow.com/questions/28509317/get-all-types-that-implement-an-interface-in-unity)的问题和建议的答案。 –