C# – 为什么我需要初始化[Out]参数

我使用以下语法从本机.dll导入了几个方法:

internal static class DllClass {
    [DllImport("Example.dll", EntryPoint = "ExampleFunction")]
    public static extern int ExampleFunction([Out] ExampleStruct param);
}

现在,因为我将param指定为[Out],我希望以下代码段中至少有一个有效:

ExampleStruct s;
DllCass.ExampleFunction(s);

ExampleStruct s;
DllCass.ExampleFunction([Out] s);

ExampleStruct s;
DllCass.ExampleFunction(out s);

但是,它们都不起作用.我发现使它工作的唯一方法是初始化s.

ExampleStruct s = new ExampleStruct();
DllCass.ExampleFunction(s);

我已经设法通过将第一个代码段重写为以下代码来解决这个问题,但这感觉有点多余.

internal static class DllClass {
    [DllImport("Example.dll", EntryPoint = "ExampleFunction")]
    public static extern int ExampleFunction([Out] out ExampleClass param);
}

我已经阅读了What’s the difference between [Out] and out in C#?,因为接受的答案表明[Out]和out在上下文中是等价的,它让我想知道为什么它对我不起作用,如果我的“解决方案”是合适的.

我应该同时使用吗?我应该只使用吗?我应该只使用[Out]吗?

最佳答案 OutAttribute确定参数的运行时行为,但它在编译时没有影响.如果要使用编译时语义,则需要out关键字.

仅使用out关键字将更改运行时编组,因此OutAttribute是可选的.有关详细信息,请参阅this answer.

点赞