use*_*156 15 c# ienumerable anonymous dynamic object
我在将一个匿名对象作为参数传递给方法时遇到问题.我想像JavaScript一样传递对象.例:
function Test(obj) {
return obj.txt;
}
console.log(Test({ txt: "test"}));
Run Code Online (Sandbox Code Playgroud)
但是在C#中,它抛出了许多例外:
class Test
{
public static string TestMethod(IEnumerable<dynamic> obj)
{
return obj.txt;
}
}
Console.WriteLine(Test.TestMethod(new { txt = "test" }));
Run Code Online (Sandbox Code Playgroud)
例外:
Ser*_*rvy 24
它看起来像你想要的:
class Test
{
public static string TestMethod(dynamic obj)
{
return obj.txt;
}
}
Run Code Online (Sandbox Code Playgroud)
您正在使用它,就好像它是单个值,而不是序列.你真的想要一个序列吗?
Gra*_*374 12
这应该做到......
class Program
{
static void Main(string[] args)
{
var test = new { Text = "test", Slab = "slab"};
Console.WriteLine(test.Text); //outputs test
Console.WriteLine(TestMethod(test)); //outputs test
}
static string TestMethod(dynamic obj)
{
return obj.Text;
}
}
Run Code Online (Sandbox Code Playgroud)