我已经编写了一个C#单元测试项目“ GameTest”,其中包含三种测试方法。另外,我还为每个测试方法添加了自定义属性“ IDAttribute”。
public class IDAttribute : Attribute
{
public IDAttribute(int id)
{
...
之后,我编写了另一个应用程序,尝试提取GameTest中的所有测试方法。
var x = Assembly.LoadFrom(@"GameTest.dll");
var types = x.GetTypes();
...
foreach unit test method we found as m [Type:MethodInfo]:
var attrs = m.GetCustomAttributes(false);
foreach (var x in attrs)
{
if (x is TestCategoryAttribute)
{
var value = (x as TestCategoryAttribute).TestCategories;
Console.WriteLine(string.Join(", ", value);
}
else if (x is IDAttribute)
{
...
这里的问题是,由于没有定义,我无法直接写“ IDAttribute” [我没有引用GameTest.dll]。如果尝试引用该dll,我们将无法获得IDAttribute的任何信息。
但是,调试时可以使用Visual Studio 2010监视功能查看ID值。
那么,这个问题有什么解决方案吗?
使用反射获取属性类型和值:
foreach (var x in attrs)
{
var attributeType = x.GetType();
if (attributeType.FullName == "ClassLibrary1.IDAttribute") // also check for attributeType.Assembly == loaded assembly, if needed
{
var id = (int)attributeType.GetProperty("ID").GetValue(x);
Console.WriteLine(id);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句