How to set a property of a C# 4 dynamic object when you have the name in another variable

后端 未结 5 545
独厮守ぢ
独厮守ぢ 2021-02-01 13:38

I\'m looking for a way to modify properties on a dynamic C# 4.0 object with the name of the property known only at runtime.

Is there a way to do something l

5条回答
  •  情歌与酒
    2021-02-01 14:07

    To add to Jonas' answer, you don't have to create a new var p. Use this approach instead:

    using System;
    using System.Dynamic;
    
    class Program
    {
        static void Main(string[] args)
        {
            dynamic expando = new ExpandoObject();
            ((IDictionary)expando)["A"] = "New val 1";
            ((IDictionary)expando)["B"] = "New val 2";
    
            Console.WriteLine(expando.A);
            Console.WriteLine(expando.B);
        }
    }
    

提交回复
热议问题