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