c# 扩展方法 入门小例
来源:互联网 发布:白银大非农数据分析 编辑:程序博客网 时间:2024/06/07 00:00
C#扩展方法 入门小例
扩展方法的定义:
l 必须是静态类,静态方法
l 第一个参数带有关键字”this”,表示把这个方法赋给哪个类型
代码说明:这里的例子是写了一个静态类,myExtension,一个扩展方法Add,表示所有的INT类型的数字都将具有调用这个Add方法的能力,条件是引入MyExtension的命名空间。
下面让我们看一下用法:
代码说明:这段代码做的事是声明了一个int类型的数字并赋值为7,然后调用Add方法的时候你将看到智能感知如下:
可以看到扩展方法用了向下方向的箭头标记。然后调用就可以了,给它任意个int,由于我用了params关键字,将自动解析为int数组,之后用rlt变量进行接收,显示出来就会看到结果:
示例2:
写了一个扩展string的方法,可以把英文标准化,例如 hEllo WORld 传递进去 将会输出,Hello World
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace wpfLab1{ public static class StrExtensenClass { public static string GetNormalFormat(this string s) { s = RemoveExtraSpace(s); string[] words = s.Split(' '); string ret = ""; foreach (var word in words) { ret += StrFstChrUpr(word) + " "; } return ret; } public static string RemoveExtraSpace(this string s) { if (s == null || s.Length <= 1) { return s; } bool lastChrIsSpace = false; string ret = ""; foreach (var chr in s) { if (chr == ' ') { if (lastChrIsSpace) { continue; } else { lastChrIsSpace = true; ret += chr; } } else { ret += chr; lastChrIsSpace = false; } } return ret; } private static string StrFstChrUpr(string s) { if (s == null || s.Length < 1) { return s; } string lowerStr = s.ToLower().Remove(0, 1); string upperStr = Char.ToUpper(s[0]).ToString(); return (upperStr + lowerStr); } }}
使用:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using wpfLab1;namespace wpfLab1{ /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void btnHello_Click(object sender, RoutedEventArgs e) { string s = "hEllo wOrLd, hi, world , aa dd dw WWdd a "; lblHello.Content = s.GetNormalFormat(); } }}
- c# 扩展方法 入门小例
- 小白文:c# 扩展方法
- C#扩展方法简单入门
- 扩展方法入门
- c#中的扩展方法
- C# 扩展方法
- C#扩展方法本质
- C#扩展方法
- 关于C#扩展方法
- C#之扩展方法
- C#2008扩展方法
- C# 扩展方法
- C#扩展方法
- C#扩展方法
- C#扩展方法
- C# 扩展方法
- C# 扩展方法[学习]
- C# 扩展方法简介
- 使用WMI操作AD时常用的属性
- iftop
- 黑马程序员:finalize() 与System.gc() 垃圾回收
- 配置SAP的WebServices以及具體的Html使用JavaScript調用格式
- Cocoa中对日期和时间的处理 NSDate
- c# 扩展方法 入门小例
- javascript取窗口的可视高度和页面的内容高度 兼容所有浏览器
- Data truncation: Truncated incorrect DOUBLE value: 'Y'
- scroll view 原理
- UITableView 详细讲解
- dell e6400 安装 mac os
- 熟悉UIWebView
- 使用JS制作弹出框的几个小问题
- MySQL源码中处理客户端不同地址族的源码