C# 访问操作&x27;s输出参数

C# 访问操作&x27;s输出参数,c#,action,out,C#,Action,Out,假设出于任何奇怪的原因(互操作事实),我有这个方法 void DoSomething(out MyStruct myStruct) { // Setting the struct members here. } 我想传递给另一个方法,如下所示: ExecuteAndProcess(Action action) { action(); // How can I access the out parameter here? } 问题是我不知道如何访问out参数;我试图将E

假设出于任何奇怪的原因(互操作事实),我有这个方法

void DoSomething(out MyStruct myStruct)
{
    // Setting the struct members here.
}
我想传递给另一个方法,如下所示:

ExecuteAndProcess(Action action)
{
    action();
    // How can I access the out parameter here?
}
问题是我不知道如何访问
out
参数
;我试图将
ExecuteAndProcess
的定义更改为

ExecuteAndProcess(Action action, ref MyStruct myStructParam) 
{ 
    action();
    var member = myStructParam.Property1;
    // ...
}
因此我可以这样调用它,希望
myStructParam
参数能够反映
myStruct
变量的变化

MyStruct myStruct = default;
ExecuteAndProcess(() => DoSomething(out myStruct), ref myStructParam);
但事实并非如此


是否有任何方法可以执行操作并访问
ExecuteAndProcess
方法中的
out
参数?


遗憾的是,我不能让
DoSomething
简单地返回结构,而不是将其作为
out
参数传递,因为它的实现是在非托管代码中进行的。

您不能专门使用
操作
类型,因为没有包含
out
参数的
操作
类型。但您可以创建自己的委托类型并使用它:

void Main()
{
    ExecuteAndProcess(DoSomething);
}

void ExecuteAndProcess(MyAction action)
{
    MyStruct myStruct;
    action(out myStruct);
    // access the out parameter here
    Console.WriteLine(myStruct.A);
}

delegate void MyAction(out MyStruct myStruct);

void DoSomething(out MyStruct myStruct)
{
    // Setting the struct members here.
    myStruct = new MyStruct{A = 1};
}

public struct MyStruct{
    public int A{get;set;}
}

非常感谢,这就是我要找的。