方法参数可以通过引用传递对象但是只读的吗?
C#:您可以使方法参数通过引用传递对象但只读吗?
例如:
void MyMethod(int x, int y, read-only MyObject obj)
其中 obj
是一个对象引用,但该对象在方法过程中不能修改。
这可以在C#中实现吗?
C#: can you make it so that a method parameter passes an object by reference but is read-only?
eg:
void MyMethod(int x, int y, read-only MyObject obj)
where obj
is an object reference but this object cannot be modified during the method.
Can this be achieved in C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不。C# 没有与 C++
const
直接类似的东西(它自己的 const 是不同的)。常见的 C# 模式是传入一个不允许修改的接口,例如 IEnumerable。您还可以创建不可变的副本或包装器。No. C# has no direct analogue to C++
const
(its own const is something different). A common C# pattern for this is to pass in a interface, such asIEnumerable
, that does not permit modifications. You can also create an immutable copy or wrapper.如果您传递的对象的类是由您编写的,那么您很幸运。
问问自己:如果 C# 有
const
功能,我希望通过对我的类的const
引用来禁止对对象执行哪些操作?然后定义一个省略禁止操作的
接口
。例如:
相应的“const”接口可能是:
现在修改类:
现在您可以使用
IConstMyClass
来表示const MyClass
。注意:有人会告诉你这还不够。如果
MyMethod
转换回MyClass
会怎样?但忽略他们。最终,实现者可以使用反射来绕过类型系统的任何方面 - 查看这个有趣的示例。阻止反射攻击的唯一选择是简单的方法:创建一个完全断开连接的克隆。
If the class of the object you're passing was written by you, then you're in luck.
Ask yourself: if C# had a
const
feature, what operations on the object would I expect to be banned through aconst
reference to my class?Then define an
interface
that leaves out the banned operations.For example:
The corresponding "const" interface might be:
Now amend the class:
Now you can use
IConstMyClass
to meanconst MyClass
.Note: there will be those who will tell you that this isn't enough. What if
MyMethod
casts back toMyClass
? But ignore them. Ultimately the implementor can use reflection to get around any aspect of the type system - see this amusing example.The only option to stop reflection attacks is the trivial approach: make a totally disconnected clone.
这在 C# 中是不可能的。
您可以通过传入不可变对象来防止这种情况。
This is not possible in C#.
You can prevent this by passing in an immutable object.
没有任何机制可以为您执行此操作。
要么传递一个一次性副本,要么在类本身中构建不变性(即使是暂时的)。
There is no mechanism that does this for you.
Either pass a throwaway copy, or build immutability, even if temporary, into the class itself.
为什么不制作该对象的副本,并在您的
obj
保持不变的情况下对该副本执行您想要的任何操作。请参阅此处如何克隆对象:深度克隆对象
why don't you make a copy of that object and do whatever you want with that copy while your
obj
remains not modified.See here how to clone your object: Deep cloning objects