如何使用反射来确定属性上是否存在属性?

时间:2012-09-20 19:09:22

标签: c# reflection

类似:How I can find Data Annotation attributes and their parameters using reflection

但是,在尝试收集自定义属性时,我总是得到相同的结果。空ScriptIgnore

PropertyInfo[] Properties = Entity.GetType().GetProperties();
foreach (PropertyInfo Property in Properties)

经过调试,这行代码

var annotes = Property.GetCustomAttributes(typeof(ScriptIgnoreAttribute), false);

(我也尝试使用true

看起来像这样

annotes | {System.Web.Script.Serialization.ScriptIgnoreAttribute[0]}

但是,Property被定义为类似

的类属性
public virtual Lot Lot { get; set; }

没有附加[ScriptIgnore]属性。此外,当我在Property上尝试这个时,就像这样定义了

[ScriptIgnore]
public virtual ICollection<Lot> Lots { get; set; }

我得到与上面相同的结果

annotes | {System.Web.Script.Serialization.ScriptIgnoreAttribute[0]}

如何使用反射来确定属性是否存在?或者其他方法,如果可能的话,我也试过

var attri = Property.Attributes;

但它不包含任何属性。

2 个答案:

答案 0 :(得分:4)

以下代码有效:

using System.Web.Script.Serialization;
public class TestAttribute
{
  [ScriptIgnore]
  public string SomeProperty1 { get; set; }

  public string SomeProperty2 { get; set; }

  public string SomeProperty3 { get; set; }

  [ScriptIgnore]
  public string SomeProperty4 { get; set; }
}

定义静态扩展名:

public static class AttributeExtension
{
  public static bool HasAttribute(this PropertyInfo target, Type attribType)
  {
    var attribs = target.GetCustomAttributes(attribType, false);
    return attribs.Length > 0;
  }
}

将以下示例代码放入方法中,它会正确地获取属性 - 顺便提一下ICollection

  var test = new TestAttribute();
  var props = (typeof (TestAttribute)).GetProperties();
  foreach (var p in props)
  {
    if (p.HasAttribute(typeof(ScriptIgnoreAttribute)))
    {
      Console.WriteLine("{0} : {1}", p.Name, attribs[0].ToString());
    }
  }

  Console.ReadLine();

注意:如果您正在使用EF动态代理类,我认为您需要使用ObjectContext.GetObjectType()来解析原始类,然后才能获取属性,因为EF生成的代理类将继承属性。

答案 1 :(得分:1)

var props = type.GetProperties()
                .Where(p => p.GetCustomAttributes().Any(a => a is ScriptIgnoreAttribute))
                .ToList();
相关问题