A keyword to reference the current object as a generic type

自作多情 提交于 2021-02-05 06:09:54

问题


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);
    }
}

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
}

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);
}

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?


回答1:


No, there is no thistype constraint. There are some musings on this topic by Eric Lippert here: Curiouser and curiouser.

Note, in particular, the CRTP (your "solution" to the problem) isn't actually a solution.




回答2:


No, there is nothing like that in C#. You're going to have to go with your self-referencing generic class definition if you want to do this at all.



来源:https://stackoverflow.com/questions/7546731/a-keyword-to-reference-the-current-object-as-a-generic-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!