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

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

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

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

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


当前回答

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

其他回答

一些解决方案不是工作的valuekind对象,我从一个json字符串获得的,也许是因为我没有一个具体的类型在我的代码,类似于对象,我将从json字符串获得,所以我是如何去做的

JsonElement myObject = System.Text.Json.JsonSerializer.Deserialize<JsonElement>(jsonStringRepresentationOfMyObject);

/*In this case I know that there is a property with 
the name Code, otherwise use TryGetProperty. This will 
still return a JsonElement*/

JsonElement propertyCode = myObject.GetProperty("Code");
        
/*Now with the JsonElement that represents the property, 
you can use several methods to retrieve the actual value, 
in this case I know that the value in the property is a string, 
so I use the GetString method on the object. If I knew the value 
was a double, then I would use the GetDouble() method on the object*/

string code = propertyCode.GetString();

这对我很有用

一旦你有了你的PropertyInfo(从GetProperty),你需要调用GetValue并传递你想要从中获取值的实例。在你的情况下:

d.GetType().GetProperty("value2").GetValue(d, null);
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);
}

类似于接受的答案,您也可以尝试GetField而不是GetProperty。

d.GetType().GetField(“value2”).获取值(d);

这取决于实际的Type是如何实现的,当GetProperty()不起作用时,它可以工作,甚至可以更快。

GetProperty/GetValue对Json数据不起作用,它总是生成一个空异常,但是,你可以尝试这种方法:

使用JsonConvert序列化你的对象:

var z = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(request));

然后直接访问它,将其转换回string:

var pn = (string)z["DynamicFieldName"];

它可以直接应用Convert.ToString(request)["DynamicFieldName"],但我还没有测试。