Not inherited from system. Object
Written by Allen Lee
In the previous article, we mentioned that IL allows you to create a class that does not inherit from system. object, which breaks some of our existing understandings. At this point, we will naturally ask why this type is allowed to exist?
Test the following C ++/CLI:Code:
1 Using Namespace System;
2
3 Public Ref Class Person
4 {
5 Public :
6 Person (string ^ Name)
7 {
8M_name=Name;
9}
10
11 Person (person % P)
12 {
13M_name=P. Name;
14}
15
16 Property string ^ Name
17 {
18 String ^ Get ()
19 {
20ReturnM_name;
21}
22 }
23
24 Private :
25 String ^ M_name;
26 } ;
27
28 Void Displaypersoninfo (person P)
29 {
30Console: writeline ("Name: {0}", P. Name );
31}
32
33 Int Main (Array < System: String ^> ^ ARGs)
34 {
35 Person ^ P = Gcnew person ( " Allen " );
36 Displaypersoninfo ( * P );
37
38 Return 0 ;
39 }
The displaypersoninfo method can only be used in C ++/CLI. You cannot dereference the reference type in C #, just as in row 36th. To handle the features of C ++/CLI, il introduces a lot of things that cannot be used in other languages.
Perhaps, as some comments have said, this is a foreshadowing to the characteristics of some languages. However, this operation has brought trouble to C. I used the method mentioned in the previous article to create a system that does not inherit from the system. the object's noinherit class, placed in noinherit. DLL, and then create a project with Visual Studio 2005, reference noinherit. DLL, and write the code in main:
1 Type T = Typeof (Noinherit );
2 Console. writeline (T. basetype = Null );
3
4 Noinherit Ni = New Noinherit ( " Noinherit " );
5 Object O = Ni As Object ;
6 If (O ! = Null )
7 {
8Console. writeline (O. GetType ());
9Console. writeline (O. tostring ());
10}
Guess what is the running result of the above Code? Normally, the running result should have only one true value, that is, the output of the second line, but in fact, the eighth line actually outputs "noinherit" correctly, and the ninth line throws accessviolationexception. In principle, the exceptions in the ninth line are unexpected, but the results in the second line are very conflicting with those in the fifth line. The output in the second line is true, indicating that the noinherit class does not inherit from system. object, but the fifth line is converted successfully. Otherwise, O should be null.
When a system is complex to a certain extent, a seemingly normal change may lead to seemingly unrelated problems. When you get a library, do you assume that all the classes in it are inherited from system. object, or do you want to verify it?