对C#方法中this参数的一点点说明

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);
        }
    }

}

理解不对的地方请大佬们指正啊。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值