我從C#4.0複製了這段代碼,其中使用了Attribute/Reflection API來控制動作:要運行的測試的數量並顯示錯誤消息。使用.NET反射和屬性來控制動作
當我運行代碼時,我得到了這個結果。
Method Method1 will be tested; reps=1; msg=; memo=
Test1
Method Method2 will be tested; reps=3; msg=; memo=abc
Test2
Test2
Test2
Method Method3 will be tested; reps=3; msg=Debugging Time!; memo=
Test3
Test3
Test3
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object
at Hello.Main() [0x00000] in <filename unknown>:0
爲什麼這是Unhandled Exception
?
的源代碼如下:
using System;
using System.Reflection;
[AttributeUsage (AttributeTargets.Method)]
public sealed class TestAttribute : Attribute
{
public int Repititions;
public string FailureMessage;
public string Memo;
public TestAttribute() : this(1) {}
public TestAttribute(int repititions) {Repititions = repititions;}
}
class Foo
{
[Test]
public void Method1()
{
Console.WriteLine("Test1");
}
[Test(3, Memo="abc")]
public void Method2()
{
Console.WriteLine("Test2");
}
[Test(3, FailureMessage="Debugging Time!")]
public void Method3()
{
Console.WriteLine("Test3");
}
}
class Hello
{
static void Main()
{
foreach (MethodInfo mi in typeof(Foo).GetMethods())
{
TestAttribute att = (TestAttribute) Attribute.GetCustomAttribute(mi, typeof(TestAttribute));
if (att != null)
Console.WriteLine("Method {0} will be tested; reps={1}; msg={2}; memo={3}", mi.Name, att.Repititions, att.FailureMessage, att.Memo);
for (int i = 0; i < att.Repititions; i++)
try
{
mi.Invoke(new Foo(), null);
}
catch (Exception ex)
{
throw new Exception ("Error: " + att.FailureMessage, ex);
}
}
}
}
看起來你在Console.WriteLine(第一個)和for語句周圍缺少範圍。 –