首页 > c# > 在字段中保存引用

在字段中保存引用 (Saving reference in a Field)

2012-09-15 c#referenceref

问题

我正在尝试以下代码:

public partial class Test: Window
{
    public Test(ref List</* Type */> LList)
    {
        [...]
        this.ListField = LList;

    }

    private  List</* Type */> ListField;
}

C#不保存“ListField”中的引用。例:

Test test = new Test(ref /* List</* Type */>-variable*/)

---------

public partial class Test: Window
{
    public Test(ref List</* Type */> LList)
    {
        [...]
        this.ListField = LList;

    }

    private  List</* Type */> ListField;

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        ListField = null;
    }
}

关闭表单后,给定的对象public Test(ref List</* Type */> LList)没有改变(它不是“空”)。

那么我如何在“ListField”中保存一个引用?

解决方法

(我确定这是重复的,但我怀疑由于术语重载而很难找到示例。)

它肯定会保存一个参考ListField。这一切都可以做到-的价值ListField永远只能是一个参考,因为List<T>是一类。

你真正想要的是保持别名行为ref,但这只适用于参数 - 永远不是字段。区分“通过引用传递”作为参数传递样式和引用本身(在类和结构之间的区别很重要)是很重要的。

基本上,你不能直接做你想做的事。您可以创建一个Wrapper<T>类,创建ListField一个Wrapper<List<T>>并将引用(按值)传递给构造函数,但您不能只使用它ref来执行您想要的操作。

问题

I'm trying out the following code:

public partial class Test: Window
{
    public Test(ref List</* Type */> LList)
    {
        [...]
        this.ListField = LList;

    }

    private  List</* Type */> ListField;
}

C# doesn't save a reference in "ListField". Example:

Test test = new Test(ref /* List</* Type */>-variable*/)

---------

public partial class Test: Window
{
    public Test(ref List</* Type */> LList)
    {
        [...]
        this.ListField = LList;

    }

    private  List</* Type */> ListField;

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        ListField = null;
    }
}

After having closed the form the Object given to public Test(ref List</* Type */> LList) has not changed (it's not "null").

SO how ca I save A reference in "ListField"?

解决方法

(I'm sure this is a duplicate, but I suspect it would be hard to find examples due to terminology overloading.)

It definitely saves a reference in ListField. That's all it can do - the value of ListField can only ever be a reference, because List<T> is a class.

What it sounds like you really want is to keep the aliasing behaviour of ref, but that only applies to parameters - never fields. It's important to distinguish between "pass by reference" as a parameter passing style, and references themselves (important in terms of the difference beteween classes and structs).

Basically, you can't do what you want directly. You could create a Wrapper<T> class, make ListField a Wrapper<List<T>> and pass a reference (by value) into the constructor, but you can't just use ref to do what you want.

相似信息