如何通过匿名类型作为参数? [英] How to pass anonymous types as parameters?

查看:256
本文介绍了如何通过匿名类型作为参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何传递匿名类型作为参数传递给其他的功能呢?考虑这个例子:

How can I pass anonymous types as parameters to other functions? Consider this example:

var query = from employee in employees select new { Name = employee.Name, Id = employee.Id };
LogEmployees(query);

变量查询这里没有强类型。我应该如何定义我LogEmployees函数来接受呢?

variable query here doesn't have strong type. How should I define my LogEmployees function to accept it?

public void LogEmployees (? list)
{
    foreach (? item in list)
    {

    }

}

在换句话说,我应该怎么用标记代替。

In other words, what should I use instead of ? marks.

推荐答案

我觉得你应该做一个类这个匿名类型。这会是我认为做的最明智的事情。但是,如果你真的不想要,你可以使用动态:

I think you should make a class for this anonymous type. That'd be the most sensible thing to do in my opinion. But if you really don't want to, you could use dynamics:

public void LogEmployees (IEnumerable<dynamic> list)
{
    foreach (dynamic item in list)
    {
        string name = item.Name;
        int id = item.Id;
    }
}

请注意,这是的的强类型的,所以,如果,例如,名称变更EmployeeName,你不会知道有一个问题,直到运行时。

Note that this is not strongly typed, so if, for example, Name changes to EmployeeName, you won't know there's a problem until runtime.

这篇关于如何通过匿名类型作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆