我想创建具有以字符串形式发送的属性的匿名对象。通过反射或其他方式(从字符串到匿名属性)可以做到这一点
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"
}
}
答案 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);