Struct and Class

xiaoxiao2021-03-06  52

Some people ask "Why can't I inherit the newguid method in System.Guid," The answer is very simple, because system.guid is the structure instead of the class. For example, the following structure and class public struct mytype {public int myinteger;} public class class 1: mytype {} This code will throw compile error content as "class1: cannot inherit from timed class mytype". Another example is as follows: public struct The compilation error is as follows: "Class1: Type in interface list is not an interface". The example provided by Microsoft is available for you to learn // Copyright (C) 2000 Microsoft Corporation . All rights reserved // struct2.csusing System;. class TheClass {public int x;} struct TheStruct {public int x;} class TestClass {public static void structtaker (TheStruct s) {sx = 5;} public static void classtaker ( {Cx = 5;} public static void main () {THECLACT A = new theStruct (); theclass b = new theclass (); AX = 1; bx = 1; structtaker (a); classTaker (b); Console.writeline ("AX = {0}", AX); console.writeline ("bx = {0}", bx);}} The output of this example is: AX = 1b.x = 5 From this example example It is seen that when a structure is passed to a method, it is only a copy, while a class is passed, passed It is a reference. So AX = output is 1, constant, and BX has changed. The difference is that the structure can be instantiated, but the class is. If you don't have New to instantiate a structure, then All fields will still be unallocated until all fields are initialized. Like the class, the structure can perform the interface. More importantly, the structure does not have inheritance, a structure cannot inherit from other classes, and cannot be Class base class. Blog Garden WLJCAN's article http://www.cnblogs.com/wljcan/archive/2004/04/19/6520.aspx

转载请注明原文地址:https://www.9cbs.com/read-116902.html

New Post(0)