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

  • 相关阅读:
    “是懒人造就了方法”——读后感
    多态性动手动脑
    数组问题随笔
    String java问题随笔
    java问题总结
    java问题随笔
    java一些问题的解答
    利用参数的值得返回来求和
    是懒人造就了方法——读后感
    大道至简读后感——JAVA伪代码
  • 原文地址:https://www.cnblogs.com/tylertang/p/13725237.html
Copyright © 2011-2022 走看看