一、通過靜態類的靜態方法進行擴展
靜態類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