2

類似:リフレクションを使用してデータ注釈の属性とそのパラメーターを見つける方法

ただし、カスタム属性を収集しようとすると、常に同じ結果が返されます。空の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;

しかし、属性は含まれていませんでした。

4

2 に答える 2

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動的プロキシクラスを使用している場合、EFで生成されたプロキシクラスは属性を継承しないObjectContext.GetObjectType()ため、属性を取得する前に、を使用して元のクラスに解決する必要があると思います。

于 2012-09-20T19:36:25.937 に答える
1
var props = type.GetProperties()
                .Where(p => p.GetCustomAttributes().Any(a => a is ScriptIgnoreAttribute))
                .ToList();
于 2012-09-20T19:22:22.043 に答える