• .NET手记-定义类和接口的扩展方法


    对于iOS开发者来说,使用扩展方法是家常便饭。因为有很多的类是有系统框架的定义的,我们不能修改或者不想修改他们的源码,但是我们又想要给他添加一些扩展方法来使用。这时定义扩展方法就是很有用的方式了,正如iOS开发中的Category一样,C#也有着相应的实现。

    下面我会给大家演示一个小Demo,来介绍如何为C#类或接口定义扩展方法。

    1.创建一个基础类,命名为GuestResponse.cs

    using System.ComponentModel.DataAnnotations;
    
    namespace PartyInvites.Models
    {
        public class GusetResponse
        {
            [Required(ErrorMessage="Please input your name")]
            public string Name { get; set; }
            [Required(ErrorMessage="Please input your email")]
            [RegularExpression(".+\@.+\..+",ErrorMessage="Please enter a valid email address")]
            public string Email { get; set; }
            [Required(ErrorMessage="Please input your phone number")]
            [RegularExpression("\d+",ErrorMessage="Please enter a valid phone number")]
            public string Phone { get; set; }
            [Required(ErrorMessage="Please specify whether you will attend")]
            public bool? WillAttend { get; set; }
    
        }
    }

    这是一个很简单的类,用于一个ASP.NET MVC项目中,下面我们需要在不改动其源码情况下为其新增扩展方法。

    2.创建一个扩展方法类,命名为MyExtensionMethods.cs

    namespace PartyInvites.Models
    {
        public static class MyExtensionMethods
        {
            public static string TestExtensionMethod(this GusetResponse guestResponse)
            {
                return guestResponse.Name;
            }
        }
    }

    其中有个扩展方法TestExtensionMethod,关键在于他的参数,this关键字将此方法标记为扩展方法。GuestResponse参数告诉.NET此扩展方法用于GuestResponse类,最后一个参数 guestResponse用于引用GuestResponse的实例。

    3.到了这一步,我们就可以直接使用此扩展方法,这里我直接在代码里面调用它。

    var guestResponse = new GusetResponse();
    var result = guestResponse.TestExtensionMethod();

    注意:只有项目和扩展方法类在同一作用域中,.NET才会识别他们。定义接口扩展方法的方式和定义类的扩展方法基本一致,大家可以自行尝试。

  • 相关阅读:
    c博客作业05--指针
    C博客作业04--数组
    C博客作业03--函数
    C博客作业02--循环结构
    C博客作业01--分支、顺序结构
    我的第一篇博客
    DS博客作业05--查找
    DS博客作业04--图
    DS博客作业03--树
    DS博客作业02--栈和队列
  • 原文地址:https://www.cnblogs.com/mantgh/p/5190369.html
Copyright © 2020-2023  润新知