gpt4 book ai didi

c# - 如何以编程方式提取 AnonymousType?

转载 作者:太空宇宙 更新时间:2023-11-03 21:23:16 27 4
gpt4 key购买 nike

我想提取 AnoymousType,这是我的代码:

static void Main(string[] args)
{
Extract(new { Name = "Yoza" });
Extract(new [] { new { Name = "Yoza" }, new { Name = "Dhika" } });
}

private static void Extract(object param = null)
{
if(param.GetType().IsArray)
{
// Do something to get everyname
// Do Something to get value of variable "Name"
}
else
{
// Do Something to get a name
// Do Something to get value of variable "Name"
}
}

如果我不将该代码放在方法中,它会像这样工作:

        var dd = new { A = "Yoza" };
var cc = new[] { new { A = "Yoza" } };

String name = dd.A;
name = cc[0].A;

问题是我想把它放在方法中。如何以编程方式提取 AnonympusType?

最佳答案

您可以选择使用反射 API 从对象中获取值,如下所示:

public class Program 
{
public static void Main()
{
Extract(new { Name = "Yoza" });
Extract(new [] { new { Name = "Yoza" }, new { Name = "Dhika" } });
}

private static void Extract(object param = null)
{
if (param.GetType().IsArray)
{
var array = param as Array;
foreach(var element in array)
{
foreach(var item in element.GetType().GetProperties())
{
Console.WriteLine(string.Format("{0}: {1}", item.Name, item.GetValue(element)));
}
}
}
else
{
foreach(var item in param.GetType().GetProperties())
{
Console.WriteLine(string.Format("{0}: {1}", item.Name, item.GetValue(param)));
item.GetValue(param);
}
}
}
}

Here正在使用 DOT NET FIDDLE。

关于c# - 如何以编程方式提取 AnonymousType?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29114243/

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