简体   繁体   English

C#:返回引用?

[英]C#: Returning a reference?

I'm attempting to cache a proxy in a C# WCF program so I don't need to create it each time I process a message for a different client, so my aim is to write a function that returns a reference to the proxy. 我试图在C#WCF程序中缓存代理,因此不需要在每次为其他客户端处理消息时都创建代理,因此我的目的是编写一个返回对代理的引用的函数。

I'm not fully conversant with C#'s return mechanisms versus "out" parameters versus "ref" parameters yet though, so was wondering if this will result in a reference to _interface being returned, or a copy, or some other behaviour. 不过,我对C#的返回机制与“输出”参数与“参考”参数还不完全了解,所以想知道这是否会导致返回对_interface的引用,副本或其他行为。

        public IInterface GetInterface
        {
            return _interface;
        }

IInterface is a reference type, so it will return a copy of the reference to the object of which class implements that interface. IInterface是引用类型,因此它将返回该引用的副本到该类实现该接口的对象。 You're still pointing to the same object, it's just that the calling code obtains a new reference to the same object for its own use. 您仍然指向同一对象,只是调用代码获取对该对象的新引用供其自己使用。

Classes are reference types. 类是引用类型。 They are implicitly passed around by copy-of-reference. 它们通过引用副本隐式传递。 So, you are passing a reference in your example, but you are passing a copy of the reference. 因此,您在示例中传递了一个引用,但是您传递了该引用的副本。 This is important to understand if you are passing it to a method that is changing the object that the reference points to on the heap. 了解是否将其传递给正在更改引用指向堆上对象的方法,这一点很重要。 In that case you are simply pointing the copy to a new object and the original reference will remain unchanged. 在这种情况下,您只是将副本指向一个新对象,而原始引用将保持不变。

On a side note, the purpose of the 'ref' modifier is to pass the actual reference itself, not a copy of said reference. 附带说明一下,“ ref”修饰符的目的是传递实际的参考文献本身,而不是所述参考文献的副本。

If concrete type implementing IInterface is in fact a class (as opposed to a struct ); 如果实现IInterface具体类型实际上是一个 (而不是struct ); then yes, your code will return only a reference to the object. 然后是的,您的代码将仅返回对该对象的引用。 (Otherwise, things are a bit more complicated .) (否则, 情况会更复杂 。)

In fact, when dealing with classes in C#, it's almost impossible to "accidentally" create a copy of the object itself. 实际上,在使用C#处理类时,几乎不可能“偶然地”创建对象本身的副本。 You'd need to explicitly call some method such as MemberwiseClone or ICloneable.Clone . 您需要显式调用某些方法,例如MemberwiseCloneICloneable.Clone

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM