我想创建一个接收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();
}
答案 0 :(得分:4)
如果您想在动态中添加属性,字段等,可以尝试使用 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
答案 1 :(得分:3)
protected dynamic getNewObject(String name, String phone, String email)
{
return new { name = name, phone = phone, email = email };
}
答案 2 :(得分:1)
使用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));
}