Skip to main content
 首页 » 编程设计

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

2024年02月06日20yyy_WW

我想提取 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。