c# 扩展方法


前两天看见扩展属性,瞬间感觉微软需要学习的东西实在是太多了,博大精深,我还差得很远,以下的扩展方法就是一个很好的东西。

现在我先建立一个model

 public class Student
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
View Code

在实际场景中,可能我们需要在这个model里需要写一些方法,一些查询等等,但是我们在设计时希望model里面只是声明属性,其它方法不放在model里面,那么怎么做到两者兼容呢,扩展方法可以帮助到你,如下:

我们建立一个扩展类,

  public static class StudentEx
    {
        public static int GetAge(this Student st)
        {
            return 1;
        }
    }

那么现在就可以直接调用了,调用如下:

Student st = new Student();
           Console.WriteLine(st.GetAge());

是不是很简单,我们可以任意在model外面为model加载扩展方法。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM