2011-07-22 35 views
5
public class Foo 
{ 
    public void DoFoo() 
    { 
     int x; 
     var coll = TheFunc("bar", out x); 
    } 

    public Func<string, int, ICollection<string>> TheFunc { get; set; } 
} 

錯誤:「參數2不應與'out'關鍵字一起傳遞。」C# - 如何傳遞一個需要out變量的函數的引用?

public class Foo 
{ 
    public void DoFoo() 
    { 
     int x; 
     var coll = TheFunc("bar", out x); 
    } 

    public Func<string, out int, ICollection<string>> TheFunc { get; set; } 
} 

錯誤:「無效的方差改性劑僅接口和委託類型參數可以被指定爲變體」。

如何在此函數中獲取out參數?

+0

看到http://stackoverflow.com/questions/1365689/cannot-use-ref-or -out-parameter-in-lambda-expressions的一些細節 – shelleybutterfly

+1

僅供參考這裏比較一般的規則是*類型參數必須是可轉換爲object *的類型。 「out int」不能轉換爲對象;你不能將「引用一個int變量」轉換爲對象。 –

回答

7

你需要讓自己的委託:

delegate ICollection<string> MyFunc(string x, out int y); 
8

定義委託類型:

public delegate ICollection<string> FooDelegate(string a, out int b); 

public class Foo 
{ 
    public void DoFoo() 
    { 
     int x; 
     var coll = TheFunc("bar", out x); 
    } 

    public FooDelegate TheFunc { get; set; } 
} 
相關問題