[英]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.