我想创建一个接收 3 个字符串作为参数并返回一个对象的方法,该对象包含引用这些字符串的三个属性。
没有要复制的“旧对象”。应在此方法中创建属性。
在C#中是用反射来做到这一点吗?如果是这样,怎么办?以下是你喜欢但我做不到的。
protected Object getNewObject(String name, String phone, String email)
{
Object newObject = new Object();
... //I can not add the variables that received by the object parameter here.
return newObject();
}
如果你想动态添加属性、字段等,你可以尝试使用Expando类
http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx
dynamic newObject = new ExpandoObject();
newObject.name = name;
newObject.phone = phone;
newObject.email = email
protected dynamic getNewObject(String name, String phone, String email)
{
return new { name = name, phone = phone, email = email };
}
使用 Expando 对象的完整示例是这样的
protected dynamic getNewObject(String name, String phone, String email)
{
// ... //I can not add the variables that received by the object parameter here.
dynamic ex = new ExpandoObject();
ex.Name = name;
ex.Phone = phone;
ex.Email = email;
return ex;
}
private void button1_Click_2(object sender, EventArgs e)
{
var ye = getNewObject("1", "2", "3");
Console.WriteLine(string.Format("Name = {0},Phone = {1},Email={2}", ye.Name, ye.Phone, ye.Email));
}