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

  • 相关阅读:
    java 找不到或无法加载主类
    navicat connect error: Authentication plugin 'caching_sha2_password' cannot be loaded
    mysql command
    the diffirent between step into and step over (java)
    20181015
    Eclipse
    游戏2048源代码
    vue的生命周期
    简单快速了解Vue.js的开发流程
    C# 连接西门子PLC
  • 原文地址:https://www.cnblogs.com/tylertang/p/13725237.html
Copyright © 2011-2022 走看看