C#對類進行擴展的兩種方式


一、通過靜態類的靜態方法進行擴展

靜態類ClassExtensions為擴展類,實現了對應類Employee和Dependent的擴展方法。

 

 

 實體類Employee

public partial class Employee
    {
        public string EmployeeNo { get; set; }
        public int Age { get; set; }
        public int GetAge()
        {
            return 100;
        }
    }
public class Dependent
    {
        public string DependentName { get; set; }
        public int Age { get; set; }
        public int GetAge()
        {
            return 50;
        }
    }
public static class ClassExtensions
    {
        public static string GetName(this Employee employee)
        {
            return "EmployeeName";
        }
        public static string GetName(this Dependent dependent)
        {
            return "DependentName";
        }
    }

調用方式:

var employee = new Employee();
            var employeeName = employee.GetName();
            var fullName = employee.FullName;
            var dependent = new Dependent();
            var dependentName = dependent.GetName();

 

二、將類定義為partial

拆分一個類、一個結構、一個接口或一個方法的定義到兩個或更多的文件中是可能的。 每個源文件包含類型或方法定義的一部分,編譯應用程序時將把所有部分組合起來。

文件Employee1

public partial class Employee
    {
        public int FullName { get; set; }
    }

 

 

官方說明:

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/partial-classes-and-methods


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM