gpt4 book ai didi

.net - 如何获取标有属性的属性的实例值?

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

我有一个标有自定义属性的类,如下所示:

public class OrderLine : Entity
{
...
[Parent]
public Order Order { get; set; }
public Address ShippingAddress{ get; set; }
...
}

我想编写一个通用方法,其中我需要获取标有 Parent 属性的实体的属性。

这是我的属性:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class ParentAttribute : Attribute
{
}

这个怎么写?

最佳答案

使用 Type.GetProperties() 和 PropertyInfo.GetValue()

    T GetPropertyValue<T>(object o)
{
T value = default(T);

foreach (System.Reflection.PropertyInfo prop in o.GetType().GetProperties())
{
object[] attrs = prop.GetCustomAttributes(typeof(ParentAttribute), false);
if (attrs.Length > 0)
{
value = (T)prop.GetValue(o, null);
break;
}
}

return value;
}

关于.net - 如何获取标有属性的属性的实例值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/208570/

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