开发者

can a method parameter pass an object by reference but be read-only?

C#: can you make it so that a method parameter passes an object by referenc开发者_高级运维e 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#?


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 as IEnumerable, that does not permit modifications. You can also create an immutable copy or wrapper.


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 a const reference to my class?

Then define an interface that leaves out the banned operations.

For example:

class MyClass 
{
    public string GetSomething() { ... }

    public void Clobber() { ... }

    public int Thing { get { ... } set { ... } }
}

The corresponding "const" interface might be:

interface IConstMyClass 
{
    public string GetSomething() { ... }

    public int Thing { get { ... } }
}

Now amend the class:

class MyClass : IConstMyClass
{

Now you can use IConstMyClass to mean const MyClass.

 void MyMethod(int x, int y, IConstMyClass obj)

Note: there will be those who will tell you that this isn't enough. What if MyMethod casts back to MyClass? 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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜