我想用一个字符串访问一个动态c#属性的值:

动态d = new {value1 = "some", value2 = "random", value3 = "value"};

如果我只有“value2”作为字符串,我如何才能得到d.value2(“random”)的值?在javascript中,我可以做d["value2"]来访问值("random"),但我不确定如何用c#和反射来做到这一点。我最接近的说法是:

“value2”d.GetType () . getproperty()……但我不知道如何从中获得实际价值。

一如既往,谢谢你的帮助!


当前回答

在Newtonsoft.Json.JsonConvert.DeserializeObject中使用dynamic:

// Get JSON string of object
var obj = new { value1 = "some", value2 = "random", value3 = "value" };
var jsonString = JsonConvert.SerializeObject(obj);

// Use dynamic with JsonConvert.DeserializeObject
dynamic d = JsonConvert.DeserializeObject(jsonString);

// output = "some"
Console.WriteLine(d["value1"]);

示例: https://dotnetfiddle.net/XGBLU1

其他回答

从动态文档中获取属性 当.GetType()返回null时,尝试这样做:

var keyValuePairs = ((System.Collections.Generic.IDictionary<string, object>)doc);
var val = keyValuePairs["propertyName"].ToObject<YourModel>;

很多时候,当您请求一个动态对象时,您会得到一个ExpandoObject(不是在上面问题的匿名但静态类型的示例中,但您提到了JavaScript和我选择的JSON解析器JsonFx,例如,生成ExpandoObject)。

如果您的动态实际上是一个ExpandoObject,您可以通过将其强制转换为IDictionary来避免反射,如http://msdn.microsoft.com/en-gb/library/system.dynamic.expandoobject.aspx所述。

一旦转换为IDictionary,就可以访问有用的方法,如.Item和.ContainsKey

public static object GetProperty(object target, string name)
{
    var site = System.Runtime.CompilerServices.CallSite<Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.GetMember(0, name, target.GetType(), new[]{Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(0,null)}));
    return site.Target(site, target);
}

添加对Microsoft.CSharp的引用。也适用于动态类型和私有属性和字段。

编辑:虽然这种方法是有效的,但是从Microsoft.VisualBasic.dll程序集中可以找到几乎快20倍的方法:

public static object GetProperty(object target, string name)
{
    return Microsoft.VisualBasic.CompilerServices.Versioned.CallByName(target, name, CallType.Get);
}

Dynamitey是一个开源的。net std库,让你像动态关键字一样调用它,但是使用一个字符串作为属性名,而不是编译器为你做它,它最终等于反射速度(这几乎不如使用动态关键字快,但这是由于动态缓存的额外开销,其中编译器静态缓存)。

Dynamic.InvokeGet(d,"value2");

这是我得到一个动态的属性值的方法:

    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)
        {

        }


    }