Why I cannot cast derived generic type to base non-generic type (through a constrain)?

纵饮孤独 提交于 2019-12-23 19:19:20

问题


Given this fictional example:

class NonGeneric
{
}

class Generic<T> : NonGeneric
    where T : NonGeneric
{
    T DoSomething()
    {
        return this; // **
    }
}

I'd expect it compiles: Generic<T> derives from NonGeneric and T must be a derived class so it satisfies its constrain.

I should be able to do this:

NonGeneric obj = new Generic<NonGeneric>();

Then there should be no problem in this instruction:

return this;

Or at least this:

return (T)this;

Unfortunately it doesn't work and above example doesn't compile with error:

Cannot convert type NonGeneric<T> to 'T'

I'm doing something wrong, and I can't see it, or it's just not allowed? Why this?


I would avoid, if possible, any workaround like the one I describe in this post (Reflection, dynamic compiled methods and so on). I would avoid dynamic objects too (design decision, I can't change that).


回答1:


Have you tried this?

T DoSomething()
{
    return this as T;
}

this is not implicitly the same as T so there is a need to cast it explicitly as in the above example.




回答2:


this is NonGeneric, T is NonGeneric, but this isn't necessarily T. They could be different subclasses, from the perspective of the compiler.

Consider the class:

class Red : NonGeneric
{
}

Then your generic class becomes:

class Generic<Red> : NonGeneric
    where Red : NonGeneric // constraint satisfied
{
    Red DoSomething()
    {
        return this;
    }
}

But this isn't Red, it's Generic<Red>, which is a different subclass of NonGeneric than Red.



来源:https://stackoverflow.com/questions/21432141/why-i-cannot-cast-derived-generic-type-to-base-non-generic-type-through-a-const

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