按引用传递的C#结构? [英] pass c# struct by reference?

查看:85
本文介绍了按引用传递的C#结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C#应用​​程序,我收到指向C ++结构中的回调/委托。我不知道,如果可以做的伎俩,但只是铸件C ++指针相应的C#结构工作得很好,所以我使用C#结构来存储数据。



现在我想通过参照结构体进行进一步的处理。




  • 我不能使用,因为它可能不会地图,完美的C ++结构。

  • 我不想更好的延迟复制结构



我怎么能这样做?






这个例子表明,结构是按值传递,而不是参考:

 使用系统; 

命名空间TestStruct
{
的struct
{
公众诠释一个;
}

类节目
{
静态无效的主要(字串[] args)
{
S S1 =新S
{
A = 1
};
美孚(S1);
Console.WriteLine(外一=+ s1.a);
}

私有静态无效美孚(S S1)
{
s1.a ++;
Console.WriteLine(内A =+ s1.a);
}

}
}



输出为

 内一= 2 
外一= 1


解决方案

这听起来像你只是想使用 REF 传递该结构参照:

 私有静态无效美孚(参考小号S1)
{
s1.a ++ ;
Console.WriteLine(内A =+ s1.a);
}

和在调用点:

 美孚(REF S1); 

请参阅我的文章在C#传递更多细节参数。



请注意比互操作的,其他的,我通常会极力推荐的的使用可变的结构是这样的。我能理解的好处虽然这里。


In my c# application i receive pointer to c++ struct in callback/delegate. I'm not sure if class can do the trick but just casting c++ pointer to appropriate c# struct works fine, so I'm using c# struct for storing data.

Now I want to pass reference to struct for further processing

  • I can't use class because it probably will not "map" perfectly to c++ struct.
  • I don't want to copy struct for better latency

How can I do that?


This example demonstrates that struct is passed by value, not by reference:

using System;

namespace TestStruct
{
    struct s
    {
        public int a;
    }

    class Program
    {
        static void Main(string[] args)
        {
            s s1 = new s
                       {
                           a = 1
                       };
            Foo(s1);
            Console.WriteLine("outer a = " + s1.a);
        }

        private static void Foo(s s1)
        {
            s1.a++;
            Console.WriteLine("inner a = " + s1.a);
        }

    }
}

Output is:

inner a = 2
outer a = 1

解决方案

It sounds like you just want to use ref to pass the struct by reference:

private static void Foo(ref s s1)
{
    s1.a++;
    Console.WriteLine("inner a = " + s1.a);
}

And at the call site:

Foo(ref s1);

See my article on parameter passing in C# for more details.

Note that other than for interop, I would normally strongly recommend against using mutable structs like this. I can understand the benefits here though.

这篇关于按引用传递的C#结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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