Differences between structures and classes in. net (C,
Static void Main (string [] args)
{
// Type
// Structure: Value Type
// Class: Reference Type
// Declared Syntax: class struct
// In the class, the constructor can assign values to fields or attributes. Constructors can be overloaded.
// However, In the constructor of the structure, values can only be assigned to fields.
// In the constructor of the structure, we need to assign values to all fields, instead of assigning values to fields selected
// Call:
PersonClass pc = new PersonClass ();
// Can the structure be New?
// Open up the space structure in the stack. new call structure Constructor
PersonStruct ps = new PersonStruct ();
Ps. M2 ();
PersonStruct. M1 ();
Console. ReadKey ();
// Constructor of structures and classes:
// Similarities: no matter the structure or class, there will be a default non-parameter constructor.
// Difference: After you write a new constructor in the class, the default non-parameter constructor is killed.
// However, if you write a new constructor in the structure, the default non-parameter constructor is still in.
//
// If we only store data, we recommend that you use a structure.
// If we want to use the object-oriented idea to develop programs, we recommend using our Class
// The structure does not have object-oriented features
// Int
}
}
Public class PersonClass
{
// Field, attribute, method, and constructor
}
Public struct PersonStruct
{
// Fields and attributes
Private string _ name;
Public string Name
{
Get {return _ name ;}
Set {_ name = value ;}
}
Private int _ age;
Public int Age
{
Get {return _ age ;}
Set {_ age = value ;}
}
Private char _ gender;
Public char Gender
{
Get {return _ gender ;}
Set {_ gender = value ;}
}
Public static void M1 ()
{
Console. WriteLine ("I Am a static method in the structure ");
}
Public void M2 ()
{
Console. WriteLine ("I am a non-static method of structure ");
}
Public PersonStruct (string name, int age, char gender)
{
// This. Name = name;
// This. Age = age;
// This. Gender = gender;
This. _ name = name;
This. _ age = age;
This. _ gender = gender;
}