Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. //my base class holding a value
  2. public abstract class A{ public int aValue; }
  3.  
  4. //derived classes that actually are stuffed into the dictionary
  5. public class B : A {...}
  6. public class C : A {...}
  7.  
  8. //wrapper class for dictionary
  9. public class MyDict : Dictionary<string, A>;
  10.  
  11. //my class using the dictionary
  12. public class MyClass {
  13.  
  14. public MyDict dict = new MyDict();//use an instance of MyDict
  15.  
  16. public MyClass() { ... //fill dict with instances of B and C }
  17.  
  18. //function to return all elements of dict having a given value
  19. public MyDict GetSubSet(int testVal) {
  20. var ret = dict.Where(e => e.Value.aValue == testVal).
  21. ToDictionary(k => k.Key, k => k.Value);
  22. return (MyDict) ret; // <- here I get a runtime InvalidCastException
  23. }
  24. }
  25.  
  26. public class MyDict : Dictionary<string, A> {
  27. public MyDict() {
  28. // Perform the default initialization here
  29. ...
  30. }
  31. public MyDict(IDictionary<string,A> dict): base(dict) {
  32. // Initialize with data from the dict if necessary
  33. ...
  34. }
  35. }
  36. ...
  37. public MyDict GetSubSet(int testVal) {
  38. var ret = dict.Where(e => e.Value.aValue == testVal).
  39. ToDictionary(k => k.Key, k => k.Value);
  40. return new MyDict(ret);
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement