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

原文地址:https://www.cnblogs.com/tylertang/p/13725237.html