2011-09-25 14 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#中没有这样的东西。如果你想要这样做,你将不得不使用自引用泛型类定义。

相关问题