Can a String[] hold System.Object inside it?

后端 未结 2 756
失恋的感觉
失恋的感觉 2020-12-31 14:38

Do you feel question is strange? yes what happened also strange. let me explain.

I have found a snippet from this Covariance and Contravariance with C# Arrays

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-31 14:59

    Your example seems to answer the question: yes, a string reference can refer a non-string object. This is not intended, however.

    Consider what you have found, a bug in the debugger.

    As Jon Skeet explains in the answer you mention, because .NET arrays have this "crazy" covaraiance even though arrays are not read-only but more like read-write, everytime one writes to an array of references the framework has to check the type of the object one tries to write to the array, and throw an ArrayTypeMismatchException if you're about to use a wrong type, like assigning an instance of Cat to an array of Dogs (a runtime Dog[]) which has been cast by "crazy" covariance into an Animal[].

    What you have demonstrated is that when we use the Immediate window of the Visual Studio debugger (or similar windows), this required type check is not done, and as a result this can lead to any type Y (except pointer types probably) being assigned to a reference type variable of any reference type X. Like this:

    X[] arrayOfX = new X[1];
    object[] arrayCastByCrazyCovariance = arrayOfX;
    Y badObject = new Y();  // or another constructor or method to get a Y
    
    // Set breakpoint here.
    // In Immediate window assign:  arrayCastByCrazyCovariance[0] = badObject
    // Detach debugger again.
    
    X anomalousReferenceVariable = arrayOfX[0];
    
    anomalousReferenceVariable.MemberOfX();  // or other bad things
    

    This can make a Cat bark like a Dog, and stuff like that.

    In the linked thread on Bypassing type safeguards, the answer by CodesInChaos shows an unrelated technique with which you can put a reference to an object of a "wrong" and unrelated type into a reference variable.

提交回复
热议问题