提取属性参数值

本文关键字:参数 属性 提取 | 更新日期: 2023-09-27 18:36:47

我可以从 NUnit 测试类库程序集中检索所有测试名称,但我还需要从传递给 Category 属性的参数中检索它们的类别名称。

例如:

[Category("text")] 
public void test() {}

我需要从 DLL 获取"text"

提取属性参数值

使用反射。

例如:

给定应用于字段的此属性:

<AttributeUsage(AttributeTargets.Field)> _
     Public NotInheritable Class DataBaseValueAttribute
    Inherits Attribute
    Private _value As Object
    Public Sub New(ByVal value As Object)
      _value = value
    End Sub
    Public Function GetValue() As Object
      Return _value
    End Function
  End Class

可以使用反射从类型中获取字段信息并获取属性:

Dim tipo As Type = GetType(YourType)
Dim fi As FieldInfo = tipo.GetField("fieldName")
Dim attribs As Atributos.DataBaseValueAttribute() = CType(fi.GetCustomAttributes(GetType(Atributos.DataBaseValueAttribute), False), Atributos.DataBaseValueAttribute())
If attribs.Count > 0 Then
   Return attribs(0).GetValue()
Else
   Return Nothing
End If

在 c# 中:

[AttributeUsage(AttributeTargets.Field)]
public sealed class DataBaseValueAttribute : Attribute
{
    private object _value;
    public DataBaseValueAttribute(object value)
    {
        _value = value;
    }
    public object GetValue()
    {
        return _value;
    }
}
Type tipo = typeof(YourType);
FieldInfo fi = tipo.GetField("fieldName");
Atributos.DataBaseValueAttribute[] attribs = (Atributos.DataBaseValueAttribute[])fi.GetCustomAttributes(typeof(Atributos.DataBaseValueAttribute), false);
if (attribs.Count > 0) {
    return attribs(0).GetValue();
} else {
    return null;
}