我有一個簡單的通用委託:關鍵字來引用當前對象作爲一個通用型
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可以處理的事情嗎?
也許已經有解決問題的模式了?
我已經向GitHub上的Roslyn團隊添加了一個提案請求,它非常接近這個確切的功能。看看這裏:https://github.com/dotnet/roslyn/issues/4332 –