Summary
Let's say I have two C # 4.0 classes, one of which inherits from the other:
class ParentKey {}
class ChildKey : ParentKey {}
I want the compiler to throw an error if I try this:
ChildKey c = new ChildKey();
ParentKey p = c;
Essentially, I want to use inheritance for reuse purposes , but I want to avoid the polymorphic behavior (or, more specifically, assign compatibility) that usually comes with it. Like private C ++ inheritance.
Example
In particular, I would like to avoid accidentally mixing ParentKey and ChildKey when using some container as keys (since their implementation of GetHashCode () or Equals () may be incompatible). For instance:
Dictionary<ParentKey, object> d = new Dictionary<ParentKey, object>();
d.Add(new ChildKey(), new object());
What i tried
, , , , ( ParentKey , ).
- IEqualityComparer ParentKey ChildKey, .
...
class ChildKey : ParentKey {
public static explicit operator ParentKey(ChildKey c) {
}
}
... CS0553: .
( "" ChildKey "" , ParentKey), #.
- ? ? .