我在一个方法的参数中无法传递匿名对象,我想像 JavaScript 中那样传递这个对象。例如:
I have a problem with passing an anonymous object as an argument in a method. I want to pass the object like in JavaScript. Example:
function Test(obj) {
return obj.txt;
}
console.log(Test({ txt: "test"}));
但是在 C# 中,它会抛出很多异常:
class Test
{
public static string TestMethod(IEnumerable<dynamic> obj)
{
return obj.txt;
}
}
Console.WriteLine(Test.TestMethod(new { txt = "test" }));
异常:
- 第1个参数:无法将“AnonymousType#1”转换为“System.Collections.Generic.IEnumerable”
- 最佳重载方法匹配“ConsoleApplication1.Test.TestMethod(System.Collections.Generic.IEnumerable)”的一些无效参数
- “System.Collections.Generic.IEnumerable”不包含名为“txt”的定义,也没有接受类型为“System.Collections.Generic.IEnumerable”的第一个参数的扩展方法“txt”可以找到(您是否缺少使用指令或程序集引用 ?)