如何获取基元数组的引用类型变量?

时间:2014-07-05 00:04:48

标签: c# oop primitive-types

所以我的问题可以用简单的代码来描述:

        double[] doubles = new double[]  { 0.01, 0.01, };
        var w2 = doubles;
        w2 = null;
        //doubles still has values

我知道结构和类之间的区别:

  

如果我们将对象复制到新变量:   点p2 = p1;   形式f2 = f1;   作为结构的p2成为p1的独立副本,具有自己独立的字段。但是在f2的情况下,我们复制的所有内容都是一个引用,结果是f1和f2都指向同一个对象。

(来源:http://www.albahari.com/valuevsreftypes.aspx

但有没有办法获得引用类型,让我通过设置doubles = null而不使用强制转换为List<double>unsafe{}来将w2设置为null?

2 个答案:

答案 0 :(得分:2)

我假设您实际上并不是doublesw2属于同一范围。我猜你正在将doubles传递到其他范围,并且你想传递引用而不是副本,以便你可以从其他上下文修改doubles

double[] doubles = new double[] { 1, 2, 3}; 

SomeMethod(ref doubles);


// This will return true
Console.WriteLine(doubles == null);


private static void SomeMethod(ref double[] w2)
{
    w2 = null;
}

答案 1 :(得分:-1)

不完全确定你想要什么,但如果你想以编程方式获得w2的类型,那么就这样做:

Type w2_type = w2.GetType();

您可以将w2_type添加到监视列表中,其值应为“{System.Double []}”