动态解析嵌套类的值和属性

发布于 2024-12-14 12:49:00 字数 732 浏览 1 评论 0原文

我有几个包含嵌套类和列表的模型。许多类成员都有我也必须读入的属性。

我正在寻找一种动态方式(可能通过 Linq 或 Reflection)来检索指定模型中所有通用对象的值和属性。

欢迎任何建议。

编辑:

按照 x0r 的建议使用 ObjectManager,我可以看到所有数据。这个问题的剩余部分需要成员注释。有没有办法复制每个类成员的 PropertyInfo?

ObjectWalker objectWalker = new ObjectWalker(objectToValidate);

foreach (Object o in objectWalker)
{
    if (isGeneric(o.GetType()))
    {    
        PropertyInfo property = o.GetType().GetProperty(o); // <-- This does not work... Need to obtain annotations somehow
        object[] Attributes = property.GetCustomAttributes(typeof(Attribute), true);

        foreach (Attribute attribute in Attributes)
        {
            // Annotations processing goes here
        }
    }
}

I have several models that includes nested classes and lists. Many of the class members have attributes that I also have to read in.

I'm looking for a dynamic way (possibly through Linq or Reflection) to retrieve the values and attributes of all generic objects within the specified model.

Any suggestions are welcome.

Edit:

Using the ObjectManager as per x0r's suggestion, I can see all of the data. The remaining part of this issue requires member annotation. Is there some way to copy over the PropertyInfo of each class member?

ObjectWalker objectWalker = new ObjectWalker(objectToValidate);

foreach (Object o in objectWalker)
{
    if (isGeneric(o.GetType()))
    {    
        PropertyInfo property = o.GetType().GetProperty(o); // <-- This does not work... Need to obtain annotations somehow
        object[] Attributes = property.GetCustomAttributes(typeof(Attribute), true);

        foreach (Attribute attribute in Attributes)
        {
            // Annotations processing goes here
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

琉璃繁缕 2024-12-21 12:49:01

查看 ObjectWalker

它可以帮助您解析对象图并访问所有独特的元素。
正如您所看到的,它只存储一堆对象,而 Current 返回一个对象。

您可以修改它,以便 Walker 保存一个类,其中包含每个属性所需的所有数据(如 propertyinfo 对象或属性列表)。

Have a look at the ObjectWalker

It helps you to parse an object graph and visit all unique elements.
As you can see it stores only a stack of objects and Current returns an Object.

You could modify this so the Walker would save a class that contains all the data you need for each property (Like a propertyinfo object or a list of attributes).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文