如何将匿名类型作为参数传递? [英] How to pass anonymous types as parameters?
问题描述
如何将匿名类型作为参数传递给其他函数?考虑这个例子:
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);
这里的变量 query
没有强类型.我应该如何定义我的 LogEmployees
函数来接受它?
The 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;
}
}
请注意,这是不是强类型的,因此,例如,如果 Name 更改为 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屋!