What are the rules for multiple casts in C #?

I have this piece of code, and I would like to know why this is output, as written in the comment below:

interface I {   
    void m1();
    void m2();      
    void m3();      
}

class A : I {
    public void m1() { Console.WriteLine("A.m1()"); }
        public virtual void m2() { Console.WriteLine("A.m2()"); }
        public virtual void m3() { Console.WriteLine("A.m3()"); }
}

class C : A, I {
    public new void m1() { Console.WriteLine("C.m1()"); }
    public override void m2() { Console.WriteLine("C.m2()"); }
    public new void m3() { Console.WriteLine("C.m3()"); }
}

------
C c = new C();

((I) ((A) c)).m1();  //"C.m1()"
((I) ((A) c)).m2();  //"C.m2()"
((I) ((A) c)).m3();  //"C.m3()"

One of the initial assumptions about what came out:

A.m1 ();
C.m2 ();
A.m3 ();

+3
source share
4 answers

All these type conversions are redundant, and I'm sure they will be optimized by the compiler.

. (A) c , C - A, (I)c, , C I. , C, .

, . , :

C , C. I.M, I - , M, S, C C, :

  • S , I M, I.M.
  • , S , M, I.M.
+1

C :

class C : A {
    public new void m1() { Console.WriteLine("C.m1()"); }
    public override void m2() { Console.WriteLine("C.m2()"); }
    public new void m3() { Console.WriteLine("C.m3()"); }
}

:

# , , , . CLR , . , ; . , ( ); .

, . . .

C I, C, , , (.. C), , C ( A ).

+4

, , - .

, C . . A. ? . . . I. ? . . . .

.

, "A" . , I, . , " , , , , " I.m1 ".

- . "". , . , " , 3 ", , - , , .

. , , "" . , , , , , I, .

?

+1

, C A I.

((I) ((A) c)). m1() ((I) ((A) c)). m3():
- "" A.m1 ( ). C.M1 C.M3.

((I) ((A) c)). m2():
- , C.M2.

0

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


All Articles