2011-09-25 27 views
3

我有一個簡單的通用委託:關鍵字來引用當前對象作爲一個通用型

delegate void CommandFinishedCallback<TCommand>(TCommand command) 
    where TCommand : CommandBase; 

我用它在以下抽象類:

public abstract class CommandBase 
{ 
    public CommandBase() 
    { } 

    public void ExecuteAsync<TCommand>(CommandFinishedCallback<TCommand> callback) 
     where TCommand : CommandBase 
    { 
     // Async stuff happens here 

     callback.Invoke(this as TCommand); 
    } 
} 

雖然這確實工作,我沒有辦法強制傳入Execute的TCommand成爲當前對象的類型(派生的CommandBase更多)。

我見過這樣解決:

public abstract class CommandBase<TCommand> 
    where TCommand : CommandBase<TCommand> 
{ 
    // class goes here 
} 

但我不知道爲什麼沒有爲完成一個C#的關鍵字?我喜歡看到的是類似以下內容:

public void ExecuteAsync<TCommand>(CommandFinishedCallback<TCommand> callback) 
    where TCommand : This 
{ 
    // Async stuff happens here 

    callback.Invoke(this); 
} 

注意「This」上的大寫字母T.我絕不是語言設計師,但我很好奇,如果我外出吃午飯或不吃東西。這是CLR可以處理的事情嗎?

也許已經有解決問題的模式了?

+0

我已經向GitHub上的Roslyn團隊添加了一個提案請求,它非常接近這個確切的功能。看看這裏:https://github.com/dotnet/roslyn/issues/4332 –

回答

2

不,沒有thistype約束。 Eric Lippert在這裏有一些關於這個話題的思考:Curiouser and curiouser

請注意,特別是,CRTP(您對問題的「解決方案」)實際上並不是解決方案。

+0

偉大的文章!謝謝。 – mbursill

0

不,在C#中沒有這樣的東西。如果你想要這樣做,你將不得不使用自引用泛型類定義。

相關問題