以通用类型引用当前对象的关键字 [英] A keyword to reference the current object as a generic type
问题描述
我有一个简单的泛型委托人:
I have a simple generic delegate:
delegate void CommandFinishedCallback<TCommand>(TCommand command)
where TCommand : CommandBase;
我在以下抽象类中使用它:
I use it in the following abstract class:
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).
While this does work, I have no way of forcing the TCommand passed into Execute to be the type of the current object (the more derived CommandBase).
我看到这样做可以解决此问题:
I've seen this solved by doing:
public abstract class CommandBase<TCommand>
where TCommand : CommandBase<TCommand>
{
// class goes here
}
但是我想知道为什么没有C#关键字来实现这一目标?我很想看的是以下内容:
But I'm wondering why there isn't a C# keyword for accomplishing that? What I'd love to see is something like the following:
public void ExecuteAsync<TCommand>(CommandFinishedCallback<TCommand> callback)
where TCommand : This
{
// Async stuff happens here
callback.Invoke(this);
}
注意"This"上的大写字母T.我绝不是语言设计师,但我很好奇我是否要去吃午餐.这会是CLR可以处理的吗?
Note the capital T on "This". I'm by no means a language designer, but I'm curious if I'm out to lunch or not. Would this be something the CLR could handle?
也许已经有解决问题的模式了?
Maybe there's already a pattern for solving the problem?
推荐答案
不,没有 thistype
约束.埃里克·利珀特(Eric Lippert)在这里对此有一些沉思:
No, there is no thistype
constraint. There are some musings on this topic by Eric Lippert here: Curiouser and curiouser.
请特别注意, CRTP (问题的解决方案")是'这实际上是一个解决方案.
Note, in particular, the CRTP (your "solution" to the problem) isn't actually a solution.
这篇关于以通用类型引用当前对象的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!