将对象作为构造函数参数传递的最佳做法是什么?传递可变对象可能会导致意想不到的结果。使用可变对象作为构造函数参数
一个简单的例子。我们预计200,但得到10000调用TestMethod的():
public class Test
{
public int TestMethod()
{
var variable1 = new SomeMeasurements
{
Width = 10,
Height = 20
};
var obj1 = new MyRectangle(variable1);
// <... more code...>
variable1.Height = 1000; // a local variable was reused here, and it's field was changed
// <... more code...>
return obj1.GetArea();
}
}
public class SomeMeasurements
{
public int Width { get; set; }
public int Height { get; set; }
}
public class MyRectangle
{
SomeMeasurements _arg;
public MyRectangle(SomeMeasurements arg)
{
_arg = arg;
}
public int GetArea()
{
return _arg.Width * _arg.Height;
}
}
在这种情况下,错误是显而易见的,但更复杂的类调试可能很乏味。几件事情如何解决这个问题已经越过我的脑海:
选项1.修复TestMethod的() - 它不能创造MyRectangle
后更改variable1
。
选项2.修复类SomeMeasurements
- 把它变成一个结构:
public struct SomeMeasurements
{
public int Width { get; set; }
public int Height { get; set; }
}
选项3.修复类SomeMeasurements
- 让一成不变的:
public class SomeMeasurements
{
public SomeMeasurements(int width, int height)
{
Width = width;
Height = height;
}
public int Width { get; }
public int Height { get; }
}
选项4。修复类MyRectangle
body - 它不得使用可变对象:
public class MyRectangle
{
int _height;
int _width;
public MyRectangle(SomeMeasurements arg)
{
_height = arg.Height;
_width = arg.Width;
}
public int GetArea()
{
return _width * _height;
}
}
选项5让SomeMeasurements
ICloneable
并用它在MyRectangle
构造Clone()
。
任何这些选项都有缺陷 - 可能很难避免重复使用变量1,MyRectangle
可能更复杂将其变成结构体,MyRectangle
可能是外部的,您可能根本不会改变它,等等。解决这个问题的最正确方法是?
另请参阅http://stackoverflow.com/questions/4327108/what-is-the-meaning-of-data-hiding –