generic type and cast

  • Thread starter Thread starter Tommaso Caldarola
  • Start date Start date
T

Tommaso Caldarola

delegate void SomeDelegate<T>() where T : BaseClass;

my_event(object sender, myEventArgs e)
{
//e.Tag object is SomeDelegate<DerivedClass>

SomeDelegate<BaseClass> del = (SomeDelegate<BaseClass>)e.Tag; // *** unable
to cast DerivedClass in BaseClass

}

How I cast (if possible) derived generic type to base generic type?


Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php
 
"Tommaso Caldarola" <[email protected]> a écrit dans le message de
[email protected]...

| delegate void SomeDelegate<T>() where T : BaseClass;
|
| my_event(object sender, myEventArgs e)
| {
| //e.Tag object is SomeDelegate<DerivedClass>
|
| SomeDelegate<BaseClass> del = (SomeDelegate<BaseClass>)e.Tag; // ***
unable
| to cast DerivedClass in BaseClass
|
| }
|
| How I cast (if possible) derived generic type to base generic type?

Sorry, this is not possible, you are trying to cast from one bound type to
another, there is no inheritance, even though the parameter type is
inherited.

You can do :

DerivedGenericType<AType> => BaseGenericType<AType>

....because the *generic* type is derived, but :

GenericType<DerivedType> => GenericType<BaseType>

....won't work because they are sibling classes rather than parent/child

Joanna
 
Back
Top