我有一對夫婦從本地.dll文件導入方法,使用的語法如下:C# - 爲什麼我需要初始化一個[out]參數
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
?我應該只使用[Out]
?
好吧,所以,假設我不想編譯時語義,具有初始化的代碼實際上是否工作? (也就是說,我會在'param'中得到一個正確的值嗎?)並且,假設我這樣做,如果我同時保持'out'和'[Out]',它會工作嗎? – rmobis 2014-10-30 12:54:58
我相信這兩個答案都是肯定的,只要外部函數寫入正確,以期望'out'參數。 – user1620220 2014-10-30 12:57:03