C#特性-擴充方法

來源:互聯網
上載者:User

標籤:

public static class PropertyExtension{        public static object GetValueByName(this object self, string propertyName)        {            if (self == null)            {                return self ;            }            Type t = self.GetType();            PropertyInfo p = t.GetProperty(propertyName);            return p.GetValue(self, null);        }}

 

擴充方法:

1 方法所在的類必須是靜態

2 方法也必須是靜態

3 方法的第一個參數必須是你要擴充的那個類型,比如你要給int擴充一個方法,那麼第一個參數就必須是int。

4 在第一個參數前面還需要有一個this關鍵字。

 

string str = "abc";
object len = str.GetValueByName("Length");

注意:

很多人看到擴充方法也許眼裡冒出金光,以後在設計的時候不管三七二十一,反正可以擴充。還有一些人會對類任意擴充,將以前一些作為”Helper”的方法統統使用擴充方法代替,注意的是擴充方法有“汙染性”,所以我覺得在擴充的時候還是想想,是不是值得這樣擴充。

在擴充的時候也不要對比較高層的類進行擴充,像我上面對object的擴充我覺得就是不可取的,object是所有類的基類,一經擴充,所有的類都被“汙染”了。

C#特性-擴充方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.