Get value of c# dynamic property via string

前端 未结 11 1721
孤城傲影
孤城傲影 2020-11-27 11:12

I\'d like to access the value of a dynamic c# property with a string:

dynamic d = new { value1 = \"some\", value2 = \"random\", value3 = \"value\"

相关标签:
11条回答
  • 2020-11-27 11:38

    This is the way i ve got the value of a property value of a dinamic:

        public dynamic Post(dynamic value)
        {            
            try
            {
                if (value != null)
                {
                    var valorCampos = "";
    
                    foreach (Newtonsoft.Json.Linq.JProperty item in value)
                    {
                        if (item.Name == "valorCampo")//property name
                            valorCampos = item.Value.ToString();
                    }                                           
    
                }
            }
            catch (Exception ex)
            {
    
            }
    
    
        }
    
    0 讨论(0)
  • 2020-11-27 11:40

    Once you have your PropertyInfo (from GetProperty), you need to call GetValue and pass in the instance that you want to get the value from. In your case:

    d.GetType().GetProperty("value2").GetValue(d, null);
    
    0 讨论(0)
  • 2020-11-27 11:40

    In .Net core 3.1 you can try like this

    d?.value2 , d?.value3
    
    0 讨论(0)
  • 2020-11-27 11:43

    Much of the time when you ask for a dynamic object, you get an ExpandoObject (not in the question's anonymous-but-statically-typed example above, but you mention JavaScript and my chosen JSON parser JsonFx, for one, generates ExpandoObjects).

    If your dynamic is in fact an ExpandoObject, you can avoid reflection by casting it to IDictionary, as described at http://msdn.microsoft.com/en-gb/library/system.dynamic.expandoobject.aspx.

    Once you've cast to IDictionary, you have access to useful methods like .Item and .ContainsKey

    0 讨论(0)
  • 2020-11-27 11:43

    d.GetType().GetProperty("value2")

    returns a PropertyInfo object.

    So then do

    propertyInfo.GetValue(d)
    
    0 讨论(0)
提交回复
热议问题