Get value from anonymous type

后端 未结 4 1394
醉酒成梦
醉酒成梦 2021-02-12 15:08

I have a method as following:

public void MyMethod(object obj){

  // implement

}

And I call it like this:

MyMethod(new { mypa         


        
4条回答
  •  难免孤独
    2021-02-12 15:43

    Well, you could use dynamic typing if you're using C# 4:

    public void MyMethod(object obj) {
        dynamic d = obj;
        Console.WriteLine(d.myparam);
    }
    

    It does beg the question of why you're not using a named type though. Anonymous types aren't really designed to be shared among different methods like this.

    EDIT: Note that if this is in a different assembly to the original code creating the object, you'll need to use [InternalsVisibleTo] as anonymous types are internal.

提交回复
热议问题