我遇到了C#泛型的麻烦:
MappingAdapter是FullMappingAdapter和LiteMappingAdapter继承/实现的常见抽象基类.
创建我的泛型类会话的实例:
session = new Session<FullMappingAdapter>(
// ...
)
Run Code Online (Sandbox Code Playgroud)
在会话中,决定我们是什么类型的会话:
// class declaration:
public class Session<T> : ISession
where T : MappingAdapter {
// ...
// method body:
T t = null;
if (t is FullMappingAdapter) {
// need parameter, cannot use where T : new() above
t = new FullMappingAdapter(someData) as T;
} else if (t is LiteMappingAdapter) {
t = new LiteMappingAdapter(someData) as T;
} else {
throw new NotSupportedException("Unknown Adapter specified, please fix.");
}
// ... more methods here ...
}
Run Code Online (Sandbox Code Playgroud)
我总是抛出NotSupportedException.另外,在调试器中查看我的堆栈时,它在t的"type"列中显示"FullMappingAdapter",这是正确的,也是我所期望的.但为什么"is"关键字也不识别这种类型呢?
我究竟做错了什么?
Ale*_*kov 10
null 从来都不是.
您想要检查typeof(T)确切的类型(或者IsAssignableFrom).
完全匹配(不一样,is FullMappingAdapter因为它不包括派生类型)
if(typeof(T) == typeof(FullMappingAdapter))
Run Code Online (Sandbox Code Playgroud)
可分配 - 与is FullMappingAdapter:相同
if (typeof(FullMappingAdapter).IsAssignableFrom(typeof(T))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |