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# 扩大要领 入门小例的内容,更多相关内容请关注ki4网(www.ki4.cn)!