gpt4 book ai didi

c# - 将当前对象引用为泛型类型的关键字

转载 作者:行者123 更新时间:2023-11-30 17:16:02 24 4
gpt4 key购买 nike

我有一个简单的通用委托(delegate):

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 可以处理的事情吗?

也许已经有解决问题的模式?

最佳答案

不,没有thistype 约束。埃里克·利珀特 (Eric Lippert) 对此主题有一些思考:Curiouser and curiouser .

请特别注意 CRTP (您对问题的“解决方案”)实际上并不是解决方案。

关于c# - 将当前对象引用为泛型类型的关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7546731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com