为了账号安全,请及时绑定邮箱和手机立即绑定

Linq快速入门——扩展方法

标签:
Linux

阅读目录

  • A simple example

  • 总结

Linq为我们提供了许多扩展方法,方便我们对数据源进行操作(Where,Select...)。即使你不了解算法,也能使用Linq当回牛人。扩展方法本质并不是什么高深的技术,说白了就是一个Static静态方法。

声明扩展方法步骤:

  • 创建一个名为MyHelper的类,约定了此类中的方法均是扩展方法。注意这个类必须是静态类(Static)

  • 扩展方法必须是Static静态方法

  • 第一个参数为待扩展的类型,前面标注this

  • 如果MyHelper在一个类库中,记得对其添加引用并using相关名称空间

回到顶部

A simple example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Linq
{
    public static  class 扩展方法Helper
    {
        public static string ToMyUpper(this string helper)
        {
            return "\""+helper.ToUpper() + "\"";
        }

        public static string Quoted(this string helper,string a,string b)
        {
            return a + helper + b;
        }
        public static bool IsNumber(this string helper)
        {
            int i;
            return int.TryParse(helper,out i);
        }
        public static string ToChineses(this bool helper)
        {
            return  helper ? "真" : "假";
        }
        public static int CreateMan(this Person helper)
        {
            Person one = new Person { Age=18,Name="Eyes"};
            return one.Age;
        }
    }
    public class Person
    {
        public int Age { get; set; }
        public string Name { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Linq
{
    class Program
    { 
        static void Main(string[] args)
        {

            Person p = new Person();
            Console.WriteLine(p.Name.IsNumber().ToChineses());
            Console.ReadKey();
        }
    }
}
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消