简体   繁体   English

如何在 c# 中循环匿名 object

[英]How to loop through anonymous object in c#

I have anonymous object looking like this:我有匿名的 object 看起来像这样:

var permissions = new
    {
        Module1 = new { view = true, delete = true },
        Module2 = new { view = true, delete = true },
    };

I tried with below code, but not working as expected我尝试使用下面的代码,但没有按预期工作

 foreach (var kp in permissions.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
    {
        var obj = kp.GetValue(Permissions, null);
        var prop = kp.Name + ",View Mode:" + obj.view ; 
    }

How can i display object Name and Value?如何显示 object 名称和值? Any help or input is highly appreciated, thanks非常感谢任何帮助或输入,谢谢

try this it will work.试试这个它会工作。

    static void Test()
    {
        var permissions = new
        {
            Module1 = new { view = false, delete = true },
            Module2 = new { view = true, delete = true },
        };

        foreach(var kp in permissions.GetType().GetTypeInfo().DeclaredProperties)
        {
            var obj = kp.GetValue(permissions);
            var objectType = obj.GetType().GetTypeInfo();

            foreach (var item in objectType.DeclaredProperties)
            {
                var prop = kp.Name + ",view mode: " + item.GetValue(obj);
            }
        }
    }

alter it, to get extract formatted output.更改它,以获取提取格式的 output。

Maybe you can try with dynamic?也许您可以尝试使用动态?

dynamic permissions = new
    {
        Module1 = new { view = true, delete = true },
        Module2 = new { view = true, delete = true },
    };

permissions.Module1.view ....

You can use System.Reflection namespace for it which contains types that retrieve information about assemblies, modules, members, parameters, and other entities in managed code by examining their metadata.您可以为其使用System.Reflection命名空间,其中包含通过检查元数据来检索托管代码中的程序集、模块、成员、参数和其他实体的信息的类型。

Here is how you can iterate through anonymous obj using this namespace:以下是使用此命名空间迭代匿名 obj 的方法:

    var permissions = new
    {
        Module1 = new { view = true, delete = true },
        Module2 = new { view = true, delete = true },
    };

    foreach(var p in permissions.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
    {
        dynamic objValue = p.GetValue(permissions, null);
        Console.WriteLine("Key {0}", ": " + p.Name); //prints obj name
        Console.WriteLine("View {0}", ": " + objValue.view); //prints 'view' parameter's value of obj 
        Console.WriteLine("Delete {0}", ": " + objValue.delete + "\n"); //prints 'delete' parameter's value of obj
    }

Read more about System.Reflection on microsoft docs .microsoft docs上阅读有关System.Reflection的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM