为什么不通过ref返回对集合的元素起作用? [英] Why doesn't returning by ref work for elements of collections?

查看:52
本文介绍了为什么不通过ref返回对集合的元素起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下通过引用返回的示例来自 C#7.0中的新增功能

The following example of returning by reference is from What’s New in C# 7.0:

public ref int Find(int number, int[] numbers)
{
    for (int i = 0; i < numbers.Length; i++)
    {
        if (numbers[i] == number)
        {
            return ref numbers[i]; // return the storage location, not the value
        }
    }
    throw new IndexOutOfRangeException($"{nameof(number)} not found");
}

该编译没有任何问题(正如您期望的那样,因为它是从Microsoft博客)。

That compiles without any problems (as you'd expect as it's copied from the Microsoft blog).

我已经写过这篇文章:

private static ref int GetReference(string searchTerm)
{
    var passwords = new Dictionary<string, int>
    {
        {"password", 1},
        {"123456", 2},
        {"12345678", 3},
        {"1234", 4},
        {"qwerty", 5},
        {"12345", 6},
        {"dragon", 7}
    };

    return ref passwords[searchTerm];
}

虽然这个没有编译;它会产生以下错误:

This one doesn't compile though; it gives the following error:


CS8156在这种情况下不能使用表达式,因为它可能不会被引用返回

CS8156 An expression cannot be used in this context because it may not be returned by reference

为什么从数组中返回却不能从集合中返回?

Why does returning from an array work, but returning from a collection doesn't?

推荐答案

答案与发布的链接相同:

The answer is in that same link you posted:


您只能返回安全返回:
传递给您,并且指向对象的字段。

You can only return refs that are "safe to return": Ones that were passed to you, and ones that point into fields in objects.

您的示例都不满足。您正在函数内部创建列表(因此对象将超出范围,并且其指针将无效),并且它不指向对象的字段。

Your example satisfies neither. You are creating the list inside the function (so the object will go out of scope and its pointer will be invalid), and it doesn't point to a field of an object.

这篇关于为什么不通过ref返回对集合的元素起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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