Why is it necessary to check the cast time when uncorking?

Why can't the compiler be detected at compile time when obj refers to an object of type B and thus reports an error when we try to apply it to type A?

public class A { }
public class B { }

static void Main(string[] args)
{
   B b = new B();
   object obj = (object)b;
   A a = (A)obj; // exception

thank

+3
source share
8 answers

The compiler can certainly implement checks that will work in trivial cases like this. But doing this is unlikely to help the very "real" code, since programmers rarely write such clearly incorrect code.

, . , , . , , , .

- . -, , , . -, ", X, , ", ", Y", , , .

, , , . , , , ! :

+6

- . , , ( ). , :

object o = SomeTest() ? (new A()) : (new B());
A a = (A)o;

SomeTest true, . , . , . , , , , - , , .

, Visual Studio 2010. , , . , !

+14

: , ? - " , , , . , , ". , , , , .

+7

, , ? ? , .

+6

. , ?

void Test(string typeName)
{
    Type t = Type.GetType(typeName);
    object obj = Activator.CreateInstance(t);
    A a = (A)obj;
    // etc.
}

? , . , - . , , .

. , , , .

, , O/R DI. - , , , , .

+2

, .

+1

, , , , , , .

, , . . , .

+1

, , , , , . :

public class A { } 
public class B { } 

static void Main(string[] args) 
{ 
   B b = new B(); 
   object obj = (object)b;
   // re-using the obj reference
   obj = new A();
   A a = (A)obj; // cast is now valid

There are so many possible permutations of the ways to reuse and use a specific base link, which the compiler author should provide. This becomes even more complicated when the obj reference is passed in the parameter to the method. Checking compilation time becomes non-deterministic, which makes compilation time potentially much longer and still does not guarantee that it can catch all invalid translations.

+1
source

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


All Articles