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(“測試通過“)]