zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    如何管理自己的文件夹
    Mybatis 笔记
    Try Catch Finally
    Java JDK安装小谈
    android 相关学习笔记
    nodejs 复制目录,调用cmd命令
    ajax图片上传,基于firefox
    一切皆命令
    javascript 之牛人感悟,必看学习
    jQuery中添加自定义或函数方法
  • 原文地址:https://www.cnblogs.com/tylertang/p/13725237.html
Copyright © 2011-2022 走看看