Get value of c# dynamic property via string

前端 未结 11 1726
孤城傲影
孤城傲影 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:20

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

    Add reference to Microsoft.CSharp. Works also for dynamic types and private properties and fields.

    Edit: While this approach works, there is almost 20× faster method from the Microsoft.VisualBasic.dll assembly:

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

提交回复
热议问题