Restricting Whether a .NET Type can be passed only ByVal or ByRef
If you create a class in .NET, is there any 开发者_如何学编程way to place a restriction on it so that if it's passed into some method (as an input parameter), then it can only be passed by reference or only passed by value?
I was thinking maybe via a attribute on the class?I believe the answer is no because ByVal and ByRef are choices made by the method, not the caller or the type designer.
However, it sounds like what you want is to create a type that you know will be immutable? Maybe you want to be sure it will NEVER be changed? Then what you can do is one of the following (not a complete list):
Create the object so that you have access to the settable properties through use of private, public, internal keywords etc.
Create the object so that the only way you can get at it's internal state is via the constructor.
Implement an interface and pass around that interface instead of the objects that implement it. The interface would be designed to only read the internal state of the object.
Prevent anyone from deriving from the object with the sealed (C#) or NotInheritable (VB) keywords.
- Class are always passed by reference.
- Struct are "always" passed by value. (but there are ways to get around that)
I'm not sure what you are trying to achieve, but can you use struct rather than class for the type that you don't user to pass by reference? Struct is ValueType as defined by the CLR.
精彩评论