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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10822092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:24:03  来源:igfitidea点击:

Passing an anonymous object as an argument in C#

c#objectdynamicienumerableanonymous

提问by user1091156

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:

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

function Test(obj) {
    return obj.txt;
}
console.log(Test({ txt: "test"}));

But in C#, it throws many exceptions:

但是在 C# 中,它会抛出很多异常:

class Test
{
    public static string TestMethod(IEnumerable<dynamic> obj)
    {
        return obj.txt;
    }
}
Console.WriteLine(Test.TestMethod(new { txt = "test" }));

Exceptions:

例外:

  1. Argument 1: cannot convert from 'AnonymousType#1' to 'System.Collections.Generic.IEnumerable'
  2. The best overloaded method match for 'ConsoleApplication1.Test.TestMethod(System.Collections.Generic.IEnumerable)' has some invalid arguments
  3. 'System.Collections.Generic.IEnumerable' does not contain a definition for 'txt' and no extension method 'txt' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?)
  1. 参数 1:无法从“AnonymousType#1”转换为“System.Collections.Generic.IEnumerable”
  2. “ConsoleApplication1.Test.TestMethod(System.Collections.Generic.IEnumerable)”的最佳重载方法匹配有一些无效参数
  3. “System.Collections.Generic.IEnumerable”不包含“txt”的定义,并且找不到接受“System.Collections.Generic.IEnumerable”类型的第一个参数的扩展方法“txt”(您是否缺少 using 指令或汇编参考?)

采纳答案by Servy

It looks like you want:

看起来你想要:

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

You're using it as if it's a single value, not a sequence. Do you really want a sequence?

你使用它就好像它是一个单一的值,而不是一个序列。你真的想要一个序列吗?

回答by Rookian

This works fine :)

这工作正常:)

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

回答by GrayFox374

This should do it...

这个应该可以...

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