C#屬性編程(二)

來源:互聯網
上載者:User
其實知道了如果編寫自己的屬性,那麼對Nunit的實現機制就可以很明白了,Nunit就是通過反射擷取測試類別中方法和類的屬性,然後進行相應處理的
假設有對象obj
Type type=obj.getType() 先擷取該對象的Type 類型
TestFixtureAttribute [] AttributeArray = (TestFixtureAttribute []) type.GetCustomAttributes(typeof(TestFixtureAttribute ), false);
通過反射獲得針對該對象的屬性定義, 比如Nunit中針對測試類別的[TestFixture]屬性
MethodInfo minfo=type.getMethod(“方法名“);
獲得該對象指定方法名的方法資訊
TestAttribute [] AttributeArray = (TestAttribute []) minfo.GetCustomAttributes(typeof(TestAttribute ), false);
獲得針對該方法的屬性定義,比如Nunit測試類別中針對方法的[Test]屬性
Nunit實在在操作中,肯定是通過type.getMethods()方法獲得所有方法資訊,然後挨個分析方法的屬性來確定那些方法需要測試的,比如當它碰到Ignore屬性的時候就會跳過測試
由此可以猜測Ignore屬性類基本是象如下定義的:
 [AttributeUsage(AttributeTargets.Method)]
 public class IgnoreAttribute : Attribute
 {
    private string describe;//描述資訊
    public IgnoreAttrebute(string info)
    {describe=info;}
    public string Describe;
    {get{..};set{..};}
}
通過設定AttributeTargets為Method表明該屬性只能為方法所用,通過一個構造方法,就強制了在使用Ignore屬性的時候必須輸入一些描述資訊,比如[Ignore(“測試通過“)]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.