是否有可能在C#中使用String值制作对象属性? 像这样:
object obj;
obj.makePropperty("username","user1");
obj.makePropperty("firstName","jnah");
obj.makePropperty("year",2014);
String getValue = obj.username;
答案 0 :(得分:2)
我认为ExpandoObject是在.NET 4.0中引入的。你可以使用它。
public dynamic MyObject { get; private set; }
MyObject = new ExpandoObject();
((IDictionary<string, object>)sourceObjectCustomFieldsExpando)Add(
<PropertyName>, <Value> );
这对字典的唯一优势是,稍后您可以使用点表示法访问属性。
((IDictionary<string, object>)MyObject)Add( "Foo", "bar" );
...
var value = MyObject.Foo;
答案 1 :(得分:1)
使用anonymous types,您可以创建一个新对象:
var newObj = new { username = "user1", firstName = "jnah", year = "2014"};
或者,如果您有一个类来代表您的对象:
public string username {get; set;}
public string firstName {get; set;}
public string year{get; set;}
var newObj = new myObj{ username = "user1", firstName = "jnah", year = "2014"};
更新:您还可以使用Dictionary或KeyValuePairs列表:
var objList= new List<KeyValuePair<string, string>>();
list.Add(new KeyValuePair<string, int>("username ", "user1"));
list.Add(new KeyValuePair<string, int>("firstName", "jnah"));
list.Add(new KeyValuePair<string, int>("year", "2014"));