【发布时间】:2013-06-01 09:16:10
【问题描述】:
为了简化使用特定类型的字典,我从通用 Dictionary 派生了一个类来处理从公共基类派生的各种元素:
//my base class holding a value
public abstract class A{ public int aValue; }
//derived classes that actually are stuffed into the dictionary
public class B : A {...}
public class C : A {...}
//wrapper class for dictionary
public class MyDict : Dictionary<string, A>;
//my class using the dictionary
public class MyClass {
public MyDict dict = new MyDict();//use an instance of MyDict
public MyClass() { ... //fill dict with instances of B and C }
//function to return all elements of dict having a given value
public MyDict GetSubSet(int testVal) {
var ret = dict.Where(e => e.Value.aValue == testVal).
ToDictionary(k => k.Key, k => k.Value);
return (MyDict) ret; // <- here I get a runtime InvalidCastException
}
}
在将通用 Dictionary 包装到 MyDict 类中之前,转换成功(如果我将 MyDict 的所有实例替换为 Dictionary<string,int>,代码工作正常,即使没有在 return 语句中转换)。
我也尝试使用return ret as MyDict; 转换结果,但这将返回一个空值。像这样通过object 进行转换:return (MyDict) (object) ret; 也会失败并出现 InvalidCastException。
有人知道如何正确转换/转换返回值吗?
【问题讨论】:
标签: c# generics casting derived