![](/img/trans.png)
[英]System.Reflection - How can I tell if a MethodInfo object is a Method or a Property accessor?
[英]How can I retrieve the value of the “Property” attribute of an NUnit Test Method using System.Reflection?
I have an NUnit test method which looks like this
[Test]
[Property("TestDescription", "Testing Subtraction of Two numbers")]
[NUnit.Framework.CategoryAttribute("mytag,subtract")]
public void TestSubtract()
{
int res = SimpleCalculator.Subtract(10,10);
//some lines of code....
}
我正在使用 C# 中的 System.Reflection 讀取此方法的屬性。 但是,我無法讀取“屬性”屬性的值,即“TestDescription”、“測試兩個數字的減法”。 我還需要讀取 CategoryAttribute 的值。 到目前為止,我還無法讀取這些值。 請幫助我。
這是我下面的代碼。 我正在從 dll 加載程序集。 然后,加載所有類型。 對於每種類型,我都在檢索 methodInfo。 對於每個 methodInfo,我都在檢索屬性。 檢索“NUnit.Framework.PropertyAttribute”后。 我需要檢索它的值。
Assembly a = Assembly.LoadFile(dllPath);
var types = a.GetTypes();
foreach(Type type in types)
{
foreach (MethodInfo methodInfo in type.GetMethods())
{
var attributes = methodInfo.GetCustomAttributes(true);
foreach (var attr in attributes)
{
if ((attr.ToString() == "NUnit.Framework.TestAttribute") || (attr.ToString() ==
"NUnit.Framework.TestCaseAttribute"))
{
//some code
}
else if((attr.ToString() == "NUnit.Framework.PropertyAttribute"))
{
//** need to retrieve the attribute value here.
}
}
}
}
您可以使用Attribute.GetCustomAttributes
來獲取所有信息。 PropertyAttribute
有點棘手,因為您可以為一個鍵分配多個值。 這是一個例子:
using NUnit.Framework;
using System;
using System.Reflection;
namespace ConsoleApp
{
static class Program
{
static void Main(string[] args)
{
string dllPath = @"C:\Path\To\MyDll.dll";
Assembly a = Assembly.LoadFrom(dllPath);
Type[] types = a.GetTypes();
foreach (Type type in types)
{
foreach (MethodInfo methodInfo in type.GetMethods())
{
PropertyAttribute[] propertyAttributes = (PropertyAttribute[])Attribute.GetCustomAttributes(methodInfo, typeof(PropertyAttribute));
foreach (PropertyAttribute attribute in propertyAttributes)
foreach (string key in attribute.Properties.Keys)
foreach (var value in attribute.Properties[key])
Console.WriteLine($"PropertyAttribute :: Key: {key} :: Value: {value}");
CategoryAttribute[] categoryAttributes = (CategoryAttribute[])Attribute.GetCustomAttributes(methodInfo, typeof(CategoryAttribute));
foreach (CategoryAttribute attribute in categoryAttributes)
Console.WriteLine($"CategoryAttribute :: Name: {attribute.Name}");
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.