简体   繁体   English

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

[英]C# - Why do I need to initialize an [Out] parameter

I have a couple of methods imported from a native .dll, using the following syntax: 我使用以下语法从本机.dll导入了几个方法:

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

Now, because I specified param as [Out] , I would expect at least one of the following snippets to be valid: 现在,因为我将param指定为[Out] ,我希望以下代码段中至少有一个有效:

ExampleStruct s;
DllCass.ExampleFunction(s);

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

ExampleStruct s;
DllCass.ExampleFunction(out s);

However, none of them works. 但是,它们都不起作用。 The only way I found to make it work was by initializing s. 我发现使它工作的唯一方法是初始化s。

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

I have managed to fix that by rewriting the first snippet to the following code, but that feels kinda redundant. 我已经设法通过将第一个代码段重写为以下代码来解决这个问题,但这感觉有点多余。

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

I've read What's the difference between [Out] and out in C#? 我已经读过C#中[Out]和out之间的区别是什么? and because the accepted answer states that [Out] and out are equivalent in the context, it left me wondering why it didn't work for me and if my "solution" is appropriate. 并且因为接受的答案表明[Out]out在上下文中是等价的,所以它让我想知道为什么它对我不起作用以及我的“解决方案”是否合适。

Should I use both? 我应该同时使用吗? Should I use only out ? 我应该只使用out Should I use only [Out] ? 我应该只使用[Out]吗?

The OutAttribute determines the runtime behavior of the parameter, but it has no impact at compile time . OutAttribute确定参数的运行时行为,但它在编译时没有影响。 The out keyword is required if you want to use compile-time semantics. 如果要使用编译时语义,则需要out关键字。

Using just the out keyword will change the runtime marshaling, so the OutAttribute is optional. 仅使用out关键字将更改运行时编组,因此OutAttribute是可选的。 See this answer for more info. 有关详细信息,请参阅此答案

Are you initializing it to a value inside the function? 您是否将其初始化为函数的值? That's where the requirement comes in: out parameters must be assigned to at least once within the function which declares the parameter. 这就是需求的来源:必须在声明参数的函数中将out参数分配至少一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM