C#方法中this参数
自我理解:在一个静态类中实现一个静态的扩展方法。
最近学习ORM框架时看到竟然可以这么搞比较吃惊,所以了解了一下。
例1:比如:string类型,你想让其实现某个功能,但由于它是一个sealed(密闭)的类,不可进行继承,但你用想让所有的string类型都实现sayHello()方法,可以使用参数this,进行方法的扩展。
using System;
using System.Windows.Forms;
namespace TestClient
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
string strTest = "张三";
strTest.SayHello();
}
}
public static class TestClass
{
public static void SayHello(this string str)
{
Console.WriteLine("Hello : " + str);
}
}
}
例2:反射中获取类中属性的特性名称,在静态类DBAttributeExtend中的泛型方法GetMappingName中对泛型的约束为MemberInfo类型,所以只有MemberInfo及其子类才能进行此方法的调用。由于PropertyInfo : MemberInfo所以可以进行调用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Dyw.CommonLib.Framework
{
public static class DBAttributeExtend
{
public static string GetMappingName<T>(this T t) where T : MemberInfo
{
if (t.IsDefined(typeof(HmsBaseAttribute), true))
{
HmsBaseAttribute attribute = (HmsBaseAttribute)t.GetCustomAttributes(typeof(HmsBaseAttribute), true)[0];
return attribute.GetName();
}
else
return t.Name;
}
}
}
——————————————————————————————————————————————————————————————————
using System;
using S
ystem.Windows.Forms;
using System.Collections.Generic;
using Dyw.CommonLib.Framework;
namespace TestClient
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
string strTest = "张三";
strTest.SayHello();
}
public List<T> GetList<T>(string sql) where T : class,new()
{
List<T> list = new List<T>();
Type type = typeof(T);
foreach (var prop in type.GetProperties())
{
string strDbName = prop.GetMappingName();
//赋值不赘述
}
return list;
}
}
public static class TestClass
{
public static void SayHello(this string str)
{
Console.WriteLine("Hello : " + str);
}
}
}
理解不对的地方请大佬们指正啊。