Bài đăng nổi bật

 


Các loại tham chiếu C# 

Trong C#, các lớp và giao diện là các kiểu tham chiếuCác biến của kiểu tham chiếu lưu trữ các tham chiếu đến dữ liệu (đối tượng) của chúng trong bộ nhớ và chúng không chứa chính dữ liệu đó.

Một đối tượng kiểu Objectstringhoặc dynamiccũng là một kiểu tham chiếu.


SportsCar scnew SportsCar(100);
SportsCar sc2sc;
sc.SpeedUp(); // Method adds 20
Console.WriteLine(sc.Speed); // 120
Console.WriteLine(sc2.Speed); // 120

// In this code, sc and sc2 refer to the same object. The last two lines will print the same value to the console.

Tham chiếu đối tượng C#

Trong C#, một đối tượng có thể được tham chiếu bởi bất kỳ kiểu nào trong hệ thống phân cấp kế thừa của nó hoặc bởi bất kỳ giao diện nào mà nó triển khai.


// Woman inherits from Human, which inherits from Animal, and it implements IPerson:
class Human : Animal
class WomanHuman, IPerson

// All of these references are valid:
Woman evenew Woman();
Human heve;
Animal aeve;
IPerson peve;

Chức năng tham chiếu đối tượng C#

Trong C#, chức năng có sẵn cho một tham chiếu đối tượng được xác định bởi kiểu của tham chiếu, không phải kiểu của đối tượng.


Player pnew Player();
Fan fp;
p.SignContract();
f.SignContract();
// Error! 'SignContract()` is not defined for the type 'Fan'

C# Polyphormism

Tính đa hình là khả năng trong lập trình trình bày cùng một giao diện cho các dạng cơ bản (kiểu dữ liệu) khác nhau.

Chúng ta có thể chia ý tưởng thành hai khái niệm liên quan. Một ngôn ngữ lập trình hỗ trợ tính đa hình nếu:

  1. Các đối tượng thuộc các loại khác nhau có một giao diện chung (giao diện theo nghĩa chung, không chỉ là giao diện C#) và
  2. Các đối tượng có thể duy trì chức năng duy nhất cho kiểu dữ liệu của chúng

class Novel : Book
{
  public override string Stringify()
  {
    return "This is a Novel!;
  }
}

class Book
{
  public virtual string Stringify()
  {
    return "This is a Book!;
  }
}

// In the below code, you’ll see that a Novel and Book object can both be referred to as Books. This is one of their shared interfaces. At the same time, they are different data types with unique functionality.

Book bknew Book();
Book warAndPeacenew Novel();
Console.WriteLine(bk.Stringify());
Console.WriteLine(warAndPeace.Stringify());

// This is a Book!
// This is a Novel

// Even though bk and warAndPeace are the same type of reference, their behavior is different. Novel overrides the Stringify() method, so all Novel objects (regardless of reference type) will use that method.

C# Upcasting

Trong C#, upcasting là tạo một lớp cha kế thừa hoặc một tham chiếu giao diện được triển khai từ một tham chiếu lớp con.


// In this case, string inherits from Object:

string s"Hi";
Object os;

// In this case, Laptop implements the IPortable interface:

Laptop lapnew Laptop();
IPortable portablelap;



C# Downcasting

Trong C#, downcasting là tạo ra một tham chiếu lớp con từ một lớp cha hoặc một tham chiếu giao diện.

Việc hạ cấp có thể dẫn đến lỗi thời gian chạy nếu lớp cha không thể được truyền sang lớp con được chỉ định.

Account a = new Account();
CustomerAccount ca = a;
// error CS0266: Cannot implicitly convert type `Account` to `CustomerAccount`. An explicit conversion exists (are you missing a cast?)

// Dog inherits from Pet. An implicit downcast throws a compile-time error:
Pet petnew Pet();
Dog dogpet;
// error CS0266: Cannot implicitly convert type `Pet` to `Dog`. An explicit conversion exists (are you missing a cast?)

// Every downcast must be explicit, using the cast operator, like (TYPE). This fixes the compile-time error but raises a new runtime error.
Pet petnew Pet();
Dog dog = (Pet)pet;
// runtime error: System.InvalidCastException: Specified cast is not valid.

//The explicit downcast would only work if the underlying object is of type Dog:
Dog dognew Dog();
Pet petdog;
Dog puppy = (Dog)pet;

Tham chiếu Null C#

Trong C#, một tham chiếu không xác định là một tham chiếu rỗng hoặc chưa được gán . Tham chiếu rỗng được đại diện bởi từ khóa null.

Hãy cẩn thận khi kiểm tra các tham chiếu rỗng và chưa được gán. Chúng tôi chỉ có thể so sánh một tham chiếu rỗng nếu nó được gắn nhãn rõ ràng null.


MyClass mc; //unassigned

Console.WriteLine (mc == null);
// error CS0165: Use of unassigned local variable 'mc'

MyClass mcnull; //explicitly 'null'

Console.WriteLine(mc == null);
// Prints true.

// Array of unassigned references
MyClass[] objectsnew MyClass[5];
// objects[0] is unassigned, objects[1] is unassigned, etc...

Các loại giá trị C#

Trong C#, các kiểu giá trị chứa chính dữ liệu. Chúng bao gồm intvà .boolchardouble

Đây là toàn bộ danh sách các loại giá trị:

  • charbool_DateTime
  • Tất cả các kiểu dữ liệu số
  • Cấu trúc ( struct)
  • Bảng kê ( enum)

Loại so sánh C #

Trong C#, kiểu so sánh được thực hiện với toán tử bình đẳng ( ==), khác với kiểu tham chiếu và giá trị.

Khi hai loại giá trị được so sánh, chúng được so sánh để bình đẳng về giá trị . Chúng bằng nhau nếu chúng có cùng giá trị.

Khi hai loại tham chiếu được so sánh, chúng được so sánh để tham chiếu bình đẳng . Chúng bằng nhau nếu chúng đề cập đến cùng một vị trí trong bộ nhớ.


// int is a value type, so == uses value equality:
int num19;
int num29;
Console.WriteLine(num1 == num2);
// Prints true

// All classes are reference types, so == uses reference equality:
WorldCupTeam japannew WorldCupTeam(2018);
WorldCupTeam brazilnew WorldCupTeam(2018);
Console.WriteLine(japan == brazil);
// Prints false
// This is because japan and brazil refer to two different locations in memory (even though they contain objects with the same values):

C# Override

Trong C#, công cụ sửa đổi override cho phép các tham chiếu lớp cơ sở đến một đối tượng dẫn xuất để truy cập các phương thức dẫn xuất.

Nói cách khác: Nếu một lớp dẫn xuất ghi đè một thành viên của lớp cơ sở của nó, thì phiên bản ghi đè có thể được truy cập bằng các tham chiếu dẫn xuất VÀ tham chiếu cơ sở.


// In the below example, DerivedClass.Method1() overrides BaseClass.Method1(). bcdc is a BaseClass-type reference to a DerivedClass value. Calling bcdc.Method1() invokes DerivedClass.Method1().

class MainClass {
  public static void Main (string[] args) {
    BaseClass bcnew BaseClass();
    DerivedClass dcnew DerivedClass();
    BaseClass bcdcnew DerivedClass();

    bc.Method1();
    dc.Method1();
    bcdc.Method1();
  }
}

class BaseClass  
{  
    public virtual void Method1()  
    {  
        Console.WriteLine("Base - Method1");  
    }  
}  

class DerivedClass : BaseClass  
{  
    public override void Method1()  
    {  
        Console.WriteLine("Derived - Method1");  
    }  
}  

// The above code produces this result:
// Base - Method1
// Derived - Method1
// Derived - Method1

// If we wanted bcdc.Method1() to invoked BaseClass.Method1(), then we would label DerivedClass.Method1() as new, not override.

Lớp đối tượng C#

Trong C#, lớp cơ sở của tất cả các kiểu là lớp ObjectMọi lớp đều kế thừa lớp này một cách ngầm định.

Khi bạn tạo một lớp không có kế thừa, C# sẽ ngầm định làm cho nó kế thừa từ Object.


// When you write this code:
class Dog {}
// C# assumes you mean:
class Dog : Object {}

//Even if your class explicitly inherits from a class that is NOT an Object, then some class in its class hierachy will inherit from Object. In the below example, Dog inherits from Pet, which inherits from Animal, which inherits from Object:
class Dog : Pet {}
class Pet : Animal {}
class Animal {}

//Since every class inherits from Object, any instance of a class can be referred to as an Object.
Dog puppynew Dog();
Object opuppy;

Phương thức lớp đối tượng C#

Trong C#, Objectlớp bao gồm các định nghĩa cho các phương thức này ToString():, Equals(Object)và GetType().


Object objnew Object();
Console.WriteLine(obj.ToString());
// The example displays the following output:
//      System.Object

public static void Main()
{
    MyBaseClass myBasenew MyBaseClass();
  MyDerivedClass myDerivednew MyDerivedClass();
  object omyDerived;
  MyBaseClass bmyDerived;

    Console.WriteLine("mybase: Type is {0}", myBase.GetType());
  Console.WriteLine("myDerived: Type is {0}", myDerived.GetType());
  Console.WriteLine("object o = myDerived: Type is {0}", o.GetType());
  Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType());
}

// The example displays the following output:
//    mybase: Type is MyBaseClass
//    myDerived: Type is MyDerivedClass
//    object o = myDerived: Type is MyDerivedClass
//    MyBaseClass b = myDerived: Type is MyDerivedClass

Phương thức C# ToString ()

Khi một đối tượng không phải chuỗi được in ra bảng điều khiển với Console.WriteLine()ToString()phương thức của nó được gọi.


Random rnew Random();

// These two lines are equivalent:
Console.WriteLine(r);
Console.WriteLine(r.ToString());

So sánh chuỗi C#

Trong C#, stringlà một kiểu tham chiếu nhưng nó có thể được so sánh bằng giá trị bằng cách sử dụng ==.


//In this example, even if s and t are not referentially equal, they are equal by value:
string s"hello";
string t"hello";

// b is true
bool b = (s == t);

Các loại chuỗi C# Bất biến

Trong C#, stringcác kiểu là bất biến , có nghĩa là chúng không thể thay đổi sau khi chúng được tạo.


// Two examples demonstrating how immutablility determines string behavior. In both examples, changing one string variable will not affect other variables that originally shared that value.

//EXAMPLE 1
string a"Hello?";
string ba;
b"HELLLLLLLO!!!!";

Console.WriteLine(b);
// Prints "HELLLLLLLO!!!!"

Console.WriteLine(a);
// Prints "Hello?"


//EXAMPLE 2
string s1"Hello ";
string s2s1;
s1 += "World";

System.Console.WriteLine(s2);
// Prints "Hello "

Chuỗi trống C#

Trong C#, một tham chiếu string có thể tham chiếu đến một chuỗi rỗng với ""và String.Empty.

Điều này tách biệt với nullvà các tham chiếu chưa được gán, cũng có thể cho các loại string.


// Empty string:
string s1"";

// Also empty string:
string s2String.Empty;

// This prints true:
Console.WriteLine(s1 == s2);

// Unassigned:
string s3;

// Null:
string s4null;


Post a Comment

أحدث أقدم