在 C# 中将匿名对象作为参数传递

本文关键字:对象 参数传递 | 更新日期: 2023-09-27 18:36:00

我在方法中将匿名对象作为参数传递时遇到问题。我想像在JavaScript中一样传递对象。例:

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. 参数 1:无法从"匿名类型#1"转换为'System.Collections.Generic.IEnumerable'
  2. 最佳重载方法匹配'ConsoleApplication1.Test.TestMethod(System.Collections.Generic.IEnumerable)'有一些无效的参数
  3. "System.Collections.Generic.IEnumerable"不包含定义"txt"并且没有扩展方法"txt"接受第一个类型为"System.Collections.Generic.IEnumerable"的参数可以找到(您是否缺少使用指令或程序集参考?

在 C# 中将匿名对象作为参数传递

看起来你想要:

class Test
{
    public static string TestMethod(dynamic obj)
    {
        return obj.txt;
    }
}

您将其用作单个值,而不是序列。 你真的想要一个序列吗?

这应该可以做到...

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;
    }
}

这:)

public class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine(Test.TestMethod(new[] {new {txt = "test"}}));
        Console.ReadLine();
    }
}
public class Test
{
    public static string TestMethod(IEnumerable<dynamic> obj)
    {
        return obj.Select(o => o.txt).FirstOrDefault();
    }
}