C# Class学习

tech2022-12-08  99

Please give me a like before reading !!!

sample:

using System; using System.Linq; namespace HelloWorld { public class Person { // Constructor that takes no arguments: public Person() { Name = "unknown"; } // Constructor that takes one argument: public Person(string name) { Name = name; } // Auto-implemented readonly property: public string Name { get; set; } // Method that overrides the base class (System.Object) implementation. public override string ToString() { return Name; } } class Program { static void Main(string[] args) { // Call the constructor that has no parameters. var person1 = new Person(); Console.WriteLine(person1.Name); // Call the constructor that has one parameter. var person2 = new Person("Sarah Jones"); Console.WriteLine(person2.Name); // Get the string representation of the person2 instance. var person3 = person2; person2.Name = "hello"; Console.WriteLine(person3); Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } }

console shows:

unknown Sarah Jones hello Press any key to exit.

Tips:

Objects can be created by two ways. first, using the new keyword followed by the name of the class that the object will be based on, like this:

var person1 = new Person();

and second like this:

var person3 = person2;

This code creates two object references that both refer to the same object. Therefore, any changes to the object made through person2 are reflected in subsequent uses of person3 . Because objects that are based on classes are referred to by reference, classes are known as reference types.

If it helps you, can you give a like ! ! Thank you ! !

最新回复(0)