如何从字符串创建匿名对象属性

时间:2018-07-04 11:16:47

标签: c# reflection anonymous

我想创建具有以字符串形式发送的属性的匿名对象。通过反射或其他方式(从字符串到匿名属性)可以做到这一点

 class Program
    {
        static void Main(string[] args)
        {

            object myobject = CreateAnonymousObjectandDoSomething("myhotproperty");
        }

        public static object CreateAnonymousObjectandDoSomething(string myproperystring)
        {
            //how can i create anonymous object from myproperystring
            return new { myproperystring = "mydata" }; //this is wrong !!
            // i want to create object like myhotproperty ="mydata"
        }
    }

1 个答案:

答案 0 :(得分:2)

您似乎正在尝试执行以下操作:

public static dynamic CreateAnonymousObjectandDoSomething(string mypropertystring)
{
    IDictionary<string, object> result = new ExpandoObject();
    result[mypropertystring] = "mydata";
    return result;
}

ExpandoObject基本上是一个字典,与dynamic一起使用时,可以像类型一样使用。

示例:

var test = CreateAnonymousObjectandDoSomething("example");
Console.WriteLine(test.example);

Try it online

相关问题