问题
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