簡體   English   中英

C# - 為什么我需要初始化[Out]參數

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

我使用以下語法從本機.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);
}

我已經讀過C#中[Out]和out之間的區別是什么? 並且因為接受的答案表明[Out]out在上下文中是等價的,所以它讓我想知道為什么它對我不起作用以及我的“解決方案”是否合適。

我應該同時使用嗎? 我應該只使用out 我應該只使用[Out]嗎?

OutAttribute確定參數的運行時行為,但它在編譯時沒有影響。 如果要使用編譯時語義,則需要out關鍵字。

僅使用out關鍵字將更改運行時編組,因此OutAttribute是可選的。 有關詳細信息,請參閱此答案

您是否將其初始化為函數的值? 這就是需求的來源:必須在聲明參數的函數中將out參數分配至少一次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM