为了简化使用特定类型的字典,我从通用Dictionary 派生了一个类,以处理从公共基类派生的各种元素://my base class holding a valuepublic abstract class A{ public int aValue; }//derived classes that actually are stuffed into the dictionarypublic class B : A {...}public class C : A {...}//wrapper class for dictionarypublic class MyDict : Dictionary<string, A>;//my class using the dictionarypublic 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。有人知道如何正确地转换/转换返回值吗? 最佳答案 您得到无效的强制转换异常,因为ToDictionary的结果不是MyDict。为了解决此问题,请在使用MyDict的IDictionary<string,A>中添加一个构造函数,并返回从GetSubSet方法调用该构造函数的结果:public class MyDict : Dictionary<string, A> { public MyDict() { // Perform the default initialization here ... } public MyDict(IDictionary<string,A> dict): base(dict) { // Initialize with data from the dict if necessary ... }}...public MyDict GetSubSet(int testVal) { var ret = dict.Where(e => e.Value.aValue == testVal). ToDictionary(k => k.Key, k => k.Value); return new MyDict(ret);}关于c# - 如何将字典的子集转换为从Dictionary <>派生的类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16943875/
10-10 19:39