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

后端 未结 5 554
独厮守ぢ
独厮守ぢ 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 13:55

    Paul Sasik answered a similar question at C# 4.0 Dynamic vs Expando... where do they fit?

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

提交回复
热议问题