Get value from anonymous type

后端 未结 4 1392
醉酒成梦
醉酒成梦 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.

    0 讨论(0)
  • 2021-02-12 15:45

    Everybody says "don't do it in the first place", but this is exactly what asp.mvc does! (Don't get me wrong I don't like it myself, but if you are writing custom html helpers you want to call them the way you call the normal html helpers...)

    And you can use asp.mvc to make your life easier:

    public void MyMethod(object obj){
      var dic=new System.Web.Routing.RouteValueDictionary(obj);
      string param=dic["myparam"] as string;
    }
    
    0 讨论(0)
  • 2021-02-12 15:50

    Use this one:

    string area = areaObject.GetType().GetProperty("area").GetValue(areaObject, null);
    
    0 讨论(0)
  • 2021-02-12 16:01

    First off, as others have said: don't do this in the first place. That's not how anonymous types were intended to be used.

    Second, if you are bent upon doing it, there are a number of ways to do so. The slow and dangerous way is to use dynamic, as others have said.

    The fast and dangerous way is to use "cast by example:

    static T CastByExample<T>(object obj, T example)
    { 
        return (T)obj; 
    }
    static void M(object obj)
    {
        var anon = CastByExample(obj, new { X = 0 });
        Console.WriteLine(anon.X);  // 123
    }
    static void N()
    {
        M(new { X = 123 });
    }
    

    is there any way to check dynamic type to if contain any property?

    Use Reflection. Of course, if you are going to use Reflection then there is no need to use dynamic in the first place. You use dynamic to avoid using Reflection, so if you are going to be using Reflection anyways, you might as well just keep on using it.

    It sounds like you are trying to do something that is hard to do in C#. I would reevaluate whether you want to be doing that, and if you do, whether C# is the language for you. A dynamic language like IronPython might be a better fit for your task.

    0 讨论(0)
提交回复
热议问题