我可以从NUnit测试类库程序集中检索所有测试名称,但我需要从传递给Category
属性的参数中检索它们的类别名称。
例如:
[Category("text")]
public void test() {}
我需要从DLL中获取"text"
。
答案 0 :(得分:1)
使用反射。
例如:
将此属性应用于字段:
<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;
}