Skip to main content
 首页 » 编程设计

c#之如何在未引用的程序集中提取方法的属性值

2024年02月13日12JustinYoung

我编写了一个 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); 
    } 
}