【发布时间】:2016-04-15 04:04:39
【问题描述】:
- 我有一个需要读取和密钥方法的通用接口。我想使用反射来获取每个实现的实例。
- 一旦我有了实现,我想获取它的键并将键和实例存储在字典中。
- 最终,我将有一个方法传入一个键和字节 [],它会在字典中查找键并使用它检索到的实例来读取字节 [] 并返回一个
object。 - 我希望这是可以理解的,否则我可以在 cmets 中回答问题。
- 这个例子只有 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<T>判断实现将具有无参数构造函数。那么你怎么知道你能够为你找到的每种类型创建一个实例呢? -
@ScottHannen 我只想将 Reader 转换为字典中定义的类型
-
看起来您正在寻找某种 IoC 容器实现。查看this 问题和建议的答案。
标签: c# generics reflection interface casting