这是不变性的良好实践吗?
早上好,
假设我有一个类
public class Class
{
int something;
int[] otherThing;
}
,并且我想使 Class
类型的对象不可变。还假设我有一个非常频繁的操作,它创建一个 Class
类型的新对象,
public Class SomeFunction()
{
int[] Temp = new int[] { ... };
return new Class(1, Temp);
}
为了避免过于频繁地创建新对象,并且由于 Temp
不再可以从方法,在构造函数上设置
this.otherThing = Temp;
而不是
otherThing = new uint[Temp.Length];
for (int i = 0; i < Temp.Length; i++)
{
this.otherThing[i] = Temp[i];
}
设置太糟糕了吗?
非常感谢。
Good morning,
Suppose I have a class
public class Class
{
int something;
int[] otherThing;
}
and I want to make objects of type Class
immutable. Suppose also that I have a very frequent operation which creates a new object of type Class
,
public Class SomeFunction()
{
int[] Temp = new int[] { ... };
return new Class(1, Temp);
}
To avoid creating new objects too often, and since Temp
is no longer accessible out of the method, is it too bad to set on the constructor
this.otherThing = Temp;
instead of
otherThing = new uint[Temp.Length];
for (int i = 0; i < Temp.Length; i++)
{
this.otherThing[i] = Temp[i];
}
?
Thank you very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果执行此操作的构造函数是私有的,那么 IMO 就很好。由于您知道另一个数组的内容永远不会改变,因此您可以直接使用它。如果您愿意,您甚至可以在类的多个实例之间共享一个数组实例,而不会造成任何问题。
另一方面,直接使用提供的数组的公共构造函数是一个坏主意。因为这可以用来打破不变性。
If the constructor that does this is private its fine IMO. Since you know the content of the other array will never change you can directly use it. You could even share one instance of the array between several instances of your class if you want to without causing any problems.
A public constructor directly using a provided array is a bad idea on the other hand. Since that can be used to break immutability.
最好将
temp
的副本分配给otherThing
,这样对otherThing
的任何更改都不会更改temp
。您还可以使用Array.CopyTo
方法用于此目的。此外,您应该认真考虑使用
IEnumerable
或IList
而不是int[]
,因为数组本质上违背了这个想法的不变性。 阅读 Eric Lippert 撰写的这篇博文。It is better to assign a copy of
temp
tootherThing
so that any changes tootherThing
will not changetemp
. You can also use theArray.CopyTo
method for this purpose.In addition you should seriously consider using
IEnumerable<int>
orIList<int>
instead ofint[]
because arrays by nature work against the idea of immutability. Read this blog post by Eric Lippert.不同之处在于,在第一个选项中,您总是获得一个新实例,而在第二个选项中,所有创建的“Class”将指向同一个数组(!)。因此,如果您更改任何类中数组中的某些内容,所有其他类都会更改。
The difference is that in the first option you always get a new instance and in the second one all the created "Class"es will point to the same array (!). So if you change something in the array in any Class, all the other classes are changed.