存放在C#中的引用 [英] Storing a reference in c#

查看:118
本文介绍了存放在C#中的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设计一个类可以更新破坏一个对象的引用(类外)。

I'm trying to design a class which can update a reference to an object (outside the class) on destruction.

所以基本上你创建这个对象的实例,并通过对它的引用类型(在任何方式,构造等),然后对目标的破坏原来的基准具有改为由对象创建的引用。

So essentially you create an instance of this object and pass it a reference type (in whichever manner, constructor etc.) and then on destruction of the object the original reference has changed to a reference created by the object.

如果我通过引用传递一个引用(在建说)我想不通的方式来存储此引用(作为参考)析构函数进行更新呢?
为例(伪):

If I pass a reference by reference (say in construction) I can't figure a way to store this reference (as a reference) for the destructor to update it? For example (pseudo):

class Updater
{
    object privateReference;
    public Updater(ref object externalReference)
    {
        privateReference = externalReference; //is privateReference now a new reference to the original object?
    }

    ~Updater()
    {
        privateReference = new object(); //therefore this isn't 'repointing' the externalReference
    }
}

这里的关键是我并不想发生变异从这个类我想原来的外部对象重新指向它,或者如果你将其初始化。

The key here is I'm not trying to mutate the original 'external' object from this class I'm trying to 'repoint' it, or initialise it if you will.

推荐答案

您不能做到这一点,基本上是这样。 REF 只适用方法本身内有效。

You can't do this, basically. ref is only applicable within the method itself, effectively.

这不是完全清楚你想用这算什么为 - 你可以给我们更多的信息,以便我们可以建议的替代设计?任何依赖于终结令人担忧有开始,说实话...

It's not at all clear what you want to use this for - could you give us more information so we can suggest alternative designs? Anything which relies on a finalizer is troubling to start with, to be honest...

这篇关于存放在C#中的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆