因为C#值类型在用作函数的参数时是transportet ByValue,而对象是ByRef传输的。所以我的问题是:什么是更好的(更快/更高性能/更少的内存)?
为您提供样本:
public void ChangeObjectByRef(MyObject mo)
{
mo.Name = "Test2";
mo.Values.Add("Value4");
}
public MyObject ChangeObjectReturnValue(MyObject mo)
{
mo.Name = "Test2";
mo.Values.Add("Value4");
return mo;
}
public void ChangeMyObject()
{
MyObject mo1 = new MyObject()
{
ID = 1,
Name = "Test",
Values = new List<string>(){
"Value1", "Value2", "Value3"
}
};
MyObject mo2 = new MyObject()
{
ID = 1,
Name = "Test",
Values = new List<string>(){
"Value1", "Value2", "Value3"
}
};
ChangeObjectByRef(mo1);
mo2 = ChangeObjectReturnValue(mo2);
Console.WriteLine(mo1.ToString());
Console.WriteLine(mo2.ToString());
}
public class MyObject
{
public int ID { get; set; }
public string Name { get; set; }
public List<string> Values { get; set; }
public override string ToString()
{
return string.Format("[ID={0}, Name={1}, Values={2}", ID, Name, string.Format("[{0}]", string.Join(", ", Values)));
}
}
结果是相同的(显而易见的)。但这两种方法之间有区别吗?
答案 0 :(得分:1)
您实际上并未使用值类型,有关值类型的详细信息,请参阅link。你实际传递的是指向该对象而不是对象本身的指针。因此,延伸@juharr在评论中的内容,当你用第一个对象的指针覆盖它时,你将失去mo2。请参阅实际发生的代码示例
class Program
{
static void Main(string[] args)
{
Demo demo = new Demo { A = "ABC" };
Demo demo2;
OptionOne(demo);
Console.WriteLine(demo.A); //Outputs World
demo2 = OptionTwo(demo);
Console.WriteLine(demo.A); //Outputs Hello
Console.WriteLine(demo2.A); //Output Hello
Console.ReadKey();
}
private static void OptionOne(Demo demo)
{
demo.A = "World";
}
private static Demo OptionTwo(Demo demo)
{
demo.A = "Hello";
return demo;
}
}
public class Demo
{
public string A { get; set; }
}