存储对值类型的引用? [英] Store a reference to a value type?

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

问题描述

我正在编写一个监视器"对象以方便调试我的应用程序.这个 Monitor 对象可以在运行时从 IronPython 解释器访问.我的问题是,是否可以在 C# 中存储对值类型的引用?假设我有以下课程:

I am writing a "Monitor" object to facilitate debugging of my app. This Monitor object can be accessed at run time from an IronPython interpreter. My question is, is it possible in C# to store a reference to a value type? Say I have the following class:

class Test
{
    public int a;
}

我可以以某种方式存储一个指向a"的指针",以便能够随时检查它的值吗?是否可以使用安全的托管代码?

Can I somehow store a "pointer" to "a" in order to be able to check it's value anytime? Is it possible using safe and managed code?

谢谢.

推荐答案

不能在字段或数组中存储对变量的引用.CLR 要求对变量的引用位于 (1) 形式参数、(2) 局部参数或 (3) 方法的返回类型中.C# 支持 (1) 但不支持其他两个.

You cannot store a reference to a variable in a field or array. The CLR requires that a reference to a variable be in (1) a formal parameter, (2) a local, or (3) the return type of a method. C# supports (1) but not the other two.

(旁白:C#可能支持另外两个功能;事实上,我已经编写了一个原型编译器来实现这些功能.它非常简洁.(参见 http://ericlippert.com/2011/06/23/ref-returns-and-ref-locals/ 了解详细信息.)当然,必须编写一种算法来验证没有 ref local 可能指代位于现已销毁的堆栈帧上的本地,这有点棘手,但是它是可行的.也许我们会在该语言的假设未来版本中支持这一点.(更新:它已添加到 C# 7!))

(ASIDE: It is possible for C# to support the other two; in fact I have written a prototype compiler that does implement those features. It's pretty neat. (See http://ericlippert.com/2011/06/23/ref-returns-and-ref-locals/ for details.) Of course one has to write an algorithm that verifies that no ref local could possibly be referring to a local that was on a now-destroyed stack frame, which gets a bit tricky, but its doable. Perhaps we will support this in a hypothetical future version of the language. (UPDATE: It was added to C# 7!))

但是,您可以通过将变量放在字段或数组中来使其具有任意长的生命周期.如果您需要的是我需要将别名存储到任意变量"意义上的引用",那么,不.但是,如果您需要的是我需要一个可以让我读写特定变量的魔法标记"意义上的引用,那么只需使用一个委托或一对委托即可.

However, you can make a variable have arbitrarily long lifetime, by putting it in a field or array. If what you need is a "reference" in the sense of "I need to store an alias to an arbitrary variable", then, no. But if what you need is a reference in the sense of "I need a magic token that lets me read and write a particular variable", then just use a delegate, or a pair of delegates.

sealed class Ref<T> 
{
    private Func<T> getter;
    private Action<T> setter;
    public Ref(Func<T> getter, Action<T> setter)
    {
        this.getter = getter;
        this.setter = setter;
    }
    public T Value
    {
        get { return getter(); }
        set { setter(value); }
    }
}
...
Ref<string> M() 
{
    string x = "hello";
    Ref<string> rx = new Ref<string>(()=>x, v=>{x=v;});
    rx.Value = "goodbye";
    Console.WriteLine(x); // goodbye
    return rx;
}

外部局部变量 x 将至少在 rx 被回收之前保持活动状态.

The outer local variable x will stay alive at least until rx is reclaimed.

这篇关于存储对值类型的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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