2015年第一次总结,我会一直努力的!!!
首先谈一谈扩展类和扩展方法的使用吧,我的理解是在一个类中不必首先声明该类,直接使用该类的属性和方法。
也可以这么理解:1、public static string TestMethod(int num)与public static string TestMethod(this int num)的区别。 两个方法返回
类型和数字签名都是一样的,就是数字
签名中一个有this一个没有this,这有什么样的区别呢?
2、string str = "Hello World"! 这是System.String类对象,那么我完全不需要在这个类中加入一个TestMethod()方
法,我就可以直接使用:str.TestMethod(),是不是很神奇??? 有人说这不可能,这个方法根本就不存在
System.String中你如何使用呢?
第一步:首先定义一个静态类ExpandClass,然后在静态类中加入该静态方法 TestMethod()
<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
<span style="color:#ff0000;">namespace TestExpand</span>
{
public static class ExpandClass
{
public static string TestMethod(<span style="color:#ff0000;">this</span> int anum)
{
return "祝大家新年快乐,万事如意!结果为:" + anum.ToString();
}
}
}</span>
第二步:在想要调用该方法的类中加入上面的命名空间: TestExpand 这里是必须要加命名空间的,即使这个类也是在该命名空间
之下也要加上。
<span style="font-size:18px;">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 <span style="color:#ff0000;">TestExpand</span>;
namespace <span style="color:#ff0000;">TestExpand</span>
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
int num= 100;
string str = <span style="color:#ff0000;">num.TestMethod();</span>
MessageBox.Show(str);
}
}
} </span>
好了,大家疑问来了:
1、num作为int整型是没有TestMethod()方法的,但是这里却直接调用了该方法?
2、一般的静态类中静态方法不都是ExpandClass.TestMethod(100);的吗?
3、TestMethod(int num)在刚才的 num.TestMethod()中没有给它传参数啊,这样真的可以吗?
是的,可以,这就是扩展类的用法了啊~
2、扩展类中扩展方法的返回值为使用该扩展方法结果成员的类型,比如上面的返回值为string那么在使用该扩展方法的返回
值的成员为string str;
3、扩展类中扩展方法的参数必须与调用该扩展方法的类型相同,比如上面 TestMethod(this int anum) 那么也只有int num整型
才可以调用;
4、调用扩展类的类中必须加扩展类的命名空间;5、扩展类中扩展方法的参数必须必须加this,不加this为普通的静态方法,不能被调用;
这只是我的个人理解,我相信会有很多不对的地方,欢迎大家指正,我都会认真接受并改正的,谢谢~!