是否有可能返回引用在C#变量? [英] Is it Possible to Return a Reference to a Variable in C#?

查看:121
本文介绍了是否有可能返回引用在C#变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以参考返回例如双重价值?

Can I return a reference to a double value for example?

这是我想做的事:

ref double GetElement()
{
   ......
   // Calculate x,y,z
   return ref doubleArray[x,y,z];
}

要使用它像这样

void func()
{
   GetElement()=5.0;
}

这就像在C ++中返回一个双指针...
我知道,这样我写的是错的..但有没有做这件事正确的方式?

It is like returning a double pointer in C++ ... I know that the way I wrote it is wrong.. but is there a correct way for doing it?

推荐答案

在C#中值类型按值总是通过。对象总是有自己的参考值传递。这就改变了不安全code作为Axarydax指出。

Value types in C# are always passed by value. Objects always have their reference passed by value. This changes in "unsafe" code as Axarydax points out.

要避免这种约束的最简单,最安全的方法是确保您的双连接到一个对象弄好了。

The easiest, safest way to avoid this constraint is to make sure that your double is attached to an object somehow.

public class MyObjectWithADouble {
    public double Element {get; set;} // property is optional, but preferred.
}

...
var obj = new MyObjectWithADouble();
obj.Element = 5.0

<击>我也想此话,我有点困惑如何您预计到三维数组分配两倍。你可能想澄清你要去什么。

我想我明白好一点你要什么了。你想给定的数组中返回值的位置,然后就可以在该位置更改值。这种模式打破了一些C#的预期范式,所以我建议考虑其他的方式来实现你在找什么。但如果真的情理之中的事,我会做这样的事情更多:

I think I understand a little better what you're going for now. You want to return the location of the value in a given array, and then be able to change the value in that location. This pattern breaks some of the expected paradigms of C#, so I would suggest considering other ways to achieve what you're looking for. But if it really makes sense to do it, I'd do something more like this:

public class 3dArrayLocation {public int X; public int Y; public int Z;}

...

public 3dArrayLocation GetElementLocation(...)
{
    // calculate x, y, and z
    return new 3dArrayLocation {X = x, Y = y, Z = z}
}

...

var location = GetElementLocation(...);
doubleArray[location.X, location.Y, location.Z] = 5.0;

这篇关于是否有可能返回引用在C#变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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