- 结论

先上结论,答案是yes,C#中数组确实具有out参数的特性。

- 疑问

最近开发一个上位机的功能,有段代码看得我一直很迷糊,我的认识,函数的执行结果,要么在函数中通过return返回,要么通过out或ref参数返回。这段代码中明显没有通过return获取返回值,输入参数倒是看起来很像out返回值,但是我反复确认了N遍,定义就是没有out或ref类型。这就很是疑惑了,只好先放一边,先把它当做out参数取返回值理解去完成开发,今天有空终于把这个疑问摸清楚了。

- 验证

各种百度,网上并没有答案。于是参照原来的代码写了一段Console程序,发现输入参数(字节数组)还真是在函数中更改后返回最新值了。此时原先的不明就里已经确定为就是【字节数组】的原因了,最初怀疑是Byte类型的原因,在程序中验证后发现并不是,然后用非字节类型的数组验证了下,仍然能在实参中取到函数更新后的值,确定为就是数组的原因。此时已经有点怀疑引用类型值类型的原因了,但是不对啊,平时引用类型string用的这么多,印象中并不会返回值啊,通过程序验证,也确定string参数没有out参数的特性,这就不得其解了。。直到搜到一篇文章,说string类型是一种特殊的引用类型,其实此处就等于是值传递,所有的谜团才清晰了。原因就在于参数分传值与传址两种,数组为引用类型,是按地址传递的,所以具备out参数的特性。
点击查看代码
class Pr
{
    private static byte[] m_byBuff = new byte[2048];
    static void Main(string[] args)
    {   

        byte[] barr_read = new byte[1024];
        int int_read = 0;
        byte byte_read=0;
        int[] iarr_read = new int[10];
        string str_read = "0";

 
        bool r = DataProcess(barr_read);
        bool r1 = DataProcess(int_read);
        bool r2 = DataProcess(byte_read);
        bool r3 = DataProcess(str_read);
        //向控制台输出
        System.Console.WriteLine("数组类型实参传参后值(传参前为0,传参函数中有赋值):");
        System.Console.WriteLine("arr[0]:{0}",barr_read[0].ToString());
        System.Console.WriteLine("arr[1]:{0}", barr_read[1].ToString());
        System.Console.WriteLine("arr[2]:{0}", barr_read[2].ToString());
        System.Console.WriteLine("arr[3]:{0}", barr_read[3].ToString());

        System.Console.WriteLine("int类型实参传参后值(传参前为0,传参函数中有赋值):");
        System.Console.WriteLine(int_read.ToString());

        System.Console.WriteLine("byte类型实参传参后值(传参前为0,传参函数中有赋值):");
        System.Console.WriteLine(byte_read.ToString());

        System.Console.WriteLine("string类型实参传参后值(传参前为‘0’,传参函数中有赋值):");
        System.Console.WriteLine(str_read);

    }
    //Main是static的,因此aa也要申明为static,否则无法访问
    private static bool DataProcess(byte[] outbuff)
    {
        outbuff[0] = (byte)1;
        outbuff[1] = (byte)2;
        outbuff[2] = (byte)3;
        outbuff[3] = (byte)4;
        return true;

    }

    private static bool DataProcess(int[] outbuff)
    {
        outbuff[0] = 11;
        outbuff[1] = 12;
        outbuff[2] = 13;
        outbuff[3] = 14;
        return true;

    }

    private static bool DataProcess(int outbuff)
    {
        outbuff=10;
        return true;

    }
    private static bool DataProcess(byte outbuff)
    {
        outbuff = 20;
        return true;

    }



    private static bool DataProcess(string outbuff)
    {
        outbuff = "30";;
        return true;

    }
}

- 参考

https://blog.csdn.net/weixin_44806070/article/details/107882525
https://www.cnblogs.com/mdnx/archive/2012/09/04/2671060.html

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/liyangxiaomeng/p/17537531.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!