通过引用传递 c# 结构?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16614704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:28:18  来源:igfitidea点击:

pass c# struct by reference?

c#

提问by javapowered

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

在我的 c# 应用程序中,我在回调/委托中收到指向 c++ 结构的指针。我不确定是否class可以做到这一点,但只是将 c++ 指针转换为适当的 c# 结构可以正常工作,所以我使用 c# 结构来存储数据。

Now I want to pass reference to struct for further processing

现在我想传递对 struct 的引用以进行进一步处理

  • I can't use classbecause it probably will not "map" perfectly to c++ struct.
  • I don't want to copy struct for better latency
  • 我不能使用,class因为它可能不会完美地“映射”到 C++ 结构。
  • 我不想复制结构以获得更好的延迟

How can I do that?

我怎样才能做到这一点?



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

这个例子演示了 struct 是按值传递的,而不是按引用传递:

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

采纳答案by Jon Skeet

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

听起来您只想使用ref通过引用传递结构:

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.

有关更多详细信息,请参阅我关于在 C# 中传递参数的文章

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

请注意,除了互操作之外,我通常强烈建议不要使用这样的可变结构。不过,我可以理解这里的好处。