Using element hiding (`new`) to get a more specific return type

I am considering using newto override members in subclasses to get a more specific return type. The question is, is this a good idea or is it asking for trouble?

The problem to be solved is that there are several “mirror” class hierarchies, where types from each hierarchical layer refer to the same level of another hierarchy. It's hard to explain, so here is an example:

class A1 {}
class A2 : A1 {}
class A3 : A2 {}

abstract class B1
{
  protected A1 myA;

  A1 MyA { get { return myA; } }
}

abstract class B2 : B1
{
  new A2 MyA { get { return (A2)myA; } }
}

class B3 : B2
{
  new A3 MyA 
  { 
    get { return (A3)myA; } 
    set { myA = value; }
  }
}

, "" 1 (A1/B1 ..), . , "" . . "", , . .

(Generics , B2 , B3 ( ). (, C1/2/3, D1/2/3...) . , .)

, (DataContractSerializer), NHibernate.

- - ? ? - ?

. - . . , .

+3
2

, ... downcasts , . IEnumerable .

, , upcast ( ).

+2

.

, , B3.MyA return (A3)(A2)this.MyA;. , b3.MyA as A3 , .

, MyA B3 A3, , A1 A2 - . .

. , , : , , . (, ), . .

Edit2. Technically it would work, but it just gets very complicated. .

. :

public abstract class B1<TA, TC> where TA: A1 where TC: A1
{
    public TA MyA { get; protected set; }
    public TC MyC { get; protected set; }
}

public abstract class B2<TA, TC> : B1<TA, TC> where TA : A2 where TC : A2
{
}

public class B3 : B2<A3, A3>
{
}

, , using, :

using ClassicB2 = MemberHiding.B2<MemberHiding.A3, MemberHiding.A3>;
ClassicB2 b3 = new B3();
+2

Source: https://habr.com/ru/post/1753665/


All Articles