Attribute.IsDefined总是返回false



我试图检查变量是否有TextArea属性,但即使有,它仍然返回false。

我在这里做错了什么?

public class Product
{
[SerializeField] string ID;
[SerializeField] string Name;
[TextArea(4, 8)]
[SerializeField] string Description;
[SerializeField] double Price;
}
Product product;
public void GetProperties()
{
PropertyInfo[] properties = product.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
Debug.Log(Attribute.IsDefined(property, typeof(TextAreaAttribute)));
}
}

我需要使用GetFields((而不是GetProperties((。

正如其他人所说,TextArea是一个字段。你应该使用这样的东西:
var fieldsWithTextAreaAttribute = typeof(Product)
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
.Where(f => f.GetCustomAttribute<TextAreaAttribute>() != null)
.ToList();

这将为您提供用TextArea注释的所有字段。然后你可以这样写GetFields()

using System.Reflection;
using System.Linq;
using System.Collections.Generic;
public List<FieldInfo> GetFieldsWithTextArea()
{
return typeof(Product)
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
.Where(f => f.GetCustomAttribute<TextAreaAttribute>() != null)
.ToList();
}

最新更新