如何从字符串创建匿名对象 属性
How can i create anonymous object property from a string
我想用 属性 创建匿名对象,以字符串形式发送。是否可以通过反射或其他东西(从字符串到匿名 属性)
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"
}
}
看起来你正在尝试做这样的事情:
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);
我想用 属性 创建匿名对象,以字符串形式发送。是否可以通过反射或其他东西(从字符串到匿名 属性)
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"
}
}
看起来你正在尝试做这样的事情:
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);