C #: How to prohibit implicit casting from a child to a parent class (i.e., inheritance in the form of a composition versus type-type)?

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; // I want compiler error here!

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()); // I want compiler error here!

What i tried

, , , , ( ParentKey , ).

- IEqualityComparer ParentKey ChildKey, .

...

class ChildKey : ParentKey {
    public static explicit operator ParentKey(ChildKey c) {
        // ...
    }
}

... CS0553: .

( "" ChildKey "" , ParentKey), #.

- ? ? .

+5
3

, . (: , - Derived to Base - Derived , ? , , .)

, , . , , -. , , . (*)

: . , Equals GetHashCode, .

(, , , "" . , .)


(*) ; . , ?

+16

:

class BaseKey
{
    // all functionality here
}

class ParentKey : BaseKey
{}

class ChildKey : BaseKey
{}

?

+5
public struct Exclusive<T>
{
   public Exclusive(T item)
   {
     if (c.GetType () != typeof(ParentKey))
       throw new Exception (); // I want compiler error here!
     Item = item;
   }
   public T Item{get; private set;}
   // todo: add implicit cast to T
   // todo: add forcing non-null to get_Item
}
0
source

All Articles