2012-06-27 36 views
0

這是我正在嘗試做的。C#.NET傳遞動態<T>方法

1類:基本分類

private void Update() 
    { 
     base.Update(Updated); 
    } 

    private void Updated(IRestResponse<thisClass> response) 
    { 
     .... 
    } 

...

基類:

public void Update(<T> callback) 
    { 
     RestClient client = new RestClient("https://www.googleapis.com"); 
     client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(App.AuthenticationResult.access_token); 
     var request = new RestRequest(path, Method.GET); 
     client.ExecuteAsync<...T...>(request, callback); 
    } 

基本上我希望能夠重用更新在多個類下面的基類的相同的結構。

+1

只是作爲一個澄清點這個被稱爲通用不是動態的(其在c#中的另一個含義) –

回答

0

當前您的基類Update方法有一些語法錯誤。

public void Update<T>(T callback) 
{ 
    RestClient client = new RestClient("https://www.googleapis.com"); 
    client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(App.AuthenticationResult.access_token); 
    var request = new RestRequest(path, Method.GET); 
    client.ExecuteAsync<T>(request, callback); 
} 

如果參數是回調不應該是委託?

它並不需要成爲這個通用的,但你可以做這樣的事情:

public delegate T CallbackDelegate<T>(); 
public void Update<T>(CallbackDelegate<T> callback) 
    { 
     RestClient client = new RestClient("https://www.googleapis.com"); 
     client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(App.AuthenticationResult.access_token); 
     var request = new RestRequest(path, Method.GET); 
     client.ExecuteAsync<T>(request, callback); 
    } 
+0

我可以提供client.ExecuteAsync (request,functionName);它工作得很好..我只是試圖提供回調函數的函數參數,以及在ExecuteAsync中使用的類型<...> ... – MatBee

+0

http://pastebin.com/nBXCZaWP – MatBee

+0

不應該回調ExecuteAsync中的參數是'callback'而不是'Updated'? –

0

我從你的問題收集的是,你要共享/重用Update()但有一個自定義Updated()擴展課程......?

可能做到這一點的最簡單的方法是創建在在擴展類中重寫基類的虛方法:

public class BaseClass 
{ 
    public virtual void Updated() { } 
    public void Update() 
    { 
     RestClient client = new RestClient("https://www.googleapis.com"); 
     client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(App.AuthenticationResult.access_token); 
     var request = new RestRequest(path, Method.GET); 

     //implement whatever logic you want with the response. 

     this.Updated(); //include whatever parameters you need to pass. 
    } 
} 

public class Class1 : BaseClass 
{ 
    public override void Updated() 
    { 
     //implement logic specific to Class1... 
    } 
}