如何将字典的子集强制转换为从Dictionary<>派生的类型

本文关键字:Dictionary 类型 派生 字典 子集 转换 | 更新日期: 2023-09-27 18:17:09

为了简化使用特定类型的字典,我从泛型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
  }
}

在mydict类中包装泛型字典之前,强制转换成功了(如果我用Dictionary<string,int>替换MyDict的所有实例,代码工作正常,即使没有在返回语句中强制转换)。

我也尝试使用return ret as MyDict;来转换结果,但这将返回一个空值。像这样通过object进行强制转换:return (MyDict) (object) ret;也会失败,并出现InvalidCastException。

有人知道如何正确地转换/转换返回值吗?

如何将字典的子集强制转换为从Dictionary<>派生的类型

由于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);
}