gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:47:46 25 4
gpt4 key购买 nike

类似: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;

但它不包含任何属性。

最佳答案

以下代码有效:

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 -生成的代理类将继承属性。

关于c# - 如何使用反射来确定属性上是否存在属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12519278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com