I have a method in Class A
public IList<T> MyMethod<T>() where T:AObject
I want to invoke this method in another generic class B. This T is without any constraints.
public mehtodInClassB(){
if (typeof(AObject)==typeof(T))
{
//Compile error here, how can I cast the T to a AObject Type
//Get the MyMethod data
A a = new A();
a.MyMethod<T>();
}
}
Class C is inherited from Class AObject.
B<C> b = new B<C>();
b.mehtodInClassB()
any thoughts?
After urs reminding...Update:
Yes. What I actually want to do is
typeof(AObject).IsAssignableFrom(typeof(T))
not
typeof(AObject)==typeof(T))
In collections there were lots of cast done. In a way, one of the main objective of Java generics is to help programmer reduce explicit type cast and provide type-safety. Before diving into detail it is better for you to go through the fundamentals of cast in Java. This is tutorial is a part of multi-part series on Java generics.
You cannot define a generic conversion operator, so you need it to be an explicit function. Moreover, a simple cast (U)t won't work, so you need Convert.ChangeType (which will work if your types are numeric). ( works as expected ). Note that Convert.ChangeType works only for types that implement IConvertible.
Oh yeah you're right. I use the double-cast in a bunch of generic designs, but it's always been for reference types. You cannot declare operators with additional generic type arguments, but you can declare ones to or from specific generic types like Point<int>.
Generic types have been around since .NET 2.0 and they can be extremely useful in creating flexible class designs that are extensible and can deal with different member types/elements. Most of the time they provide great enhancements, but dealing with casting in generics can become very complex especially if there are interdependencies in object.
If you know that T
is an AObject
, why not just provide AObject
as the type parameter to MyMethod
:
if (typeof(AObject).IsAssignableFrom(typeof(T)))
{
//Compile error here, how can I cast the T to a AObject Type
//Get the MyMethod data
d.MyMethod<AObject>();
}
If providing AObject
as a type parameter is not an option, you'll have to put the same constraint on T
in the calling method:
void Caller<T>() where T: AObject
{
// ...
d.MyMethod<T>();
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With