前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Linq快速入门——扩展方法

Linq快速入门——扩展方法

作者头像
用户1161731
发布2018-01-11 11:52:49
5700
发布2018-01-11 11:52:49
举报
文章被收录于专栏:木宛城主

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

  • 创建一个名为MyHelper的类,约定了此类中的方法均是扩展方法。注意这个类必须是静态类(Static)
  • 扩展方法必须是Static静态方法
  • 第一个参数为待扩展的类型,前面标注this
  • 如果MyHelper在一个类库中,记得对其添加引用并using相关名称空间

A simple example

代码语言:javascript
复制
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; }
    }
}
代码语言:javascript
复制
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();
        }
    }
}

总结

系列完善中,请持续关注...

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2012-08-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • A simple example
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档