Reputation: 107
I am beginner of C#, and have problem that keep bothers me.
I will very appreciated if someone makes a solution.
I have a code something like :
public class SomeClass
{
public SomeClass()
{
GenericMethod<Object1>(out result);
....
}
public void GenericMethod<T>(out Result result) where T : Parent
{
T t = new T();
//do something need to be done all parent's child object ( Object1, Object2..)
...somthing same things...
//and do specific things to be done relatively
Handle(t, result);
}
// Object1 is child of Parent
private void Handle(Object1 arg1, out Result result)
{
//do something need to be done for Object1;
}
// Object1 is child of Parent
private void Handle(Object2 arg1, out Result result)
{
//do something need to be done for Object2;
}
....
}
as you will discover, what I want to do is simple.
make specified value with Type T in GenericMethod, and invoke the specified Handle Method. It will works in C++, but C# keep telling me like
"cannot convert 'T' expression to type 'Object1'"
How can I solve this problem ? Thanx in advance.
Upvotes: 0
Views: 129
Reputation: 1007
Thats because C++ generic methods and types are constructed at compile type. So when you call GenericMethod the compiler will build that code for you, and will know whitch Handle method to call.
The C++ code will look like this after the compiler builds the method for you:
public class SomeClass
{
public SomeClass()
{
GenericMethod<Object1>(out result);
....
}
public void GenericMethod<Object1>(out Result result)
{
Object1 t = new Object1();
Handle(t, result);
}
private void Handle(Object1 arg1, out Result result)
{
//do something need to be done for Object1;
}
private void Handle(Object2 arg1, out Result result)
{
//do something need to be done for Object2;
}
....
}
As you can see it is now very clear what Handle
method the compiler will use.
C# generics are compiled at runtime. The compiler sees a call to a Handle
method with an unkown type, so the compiler complains when you want to call a method with an unkonwn type at compile time.
You can actualy use the Handle
method in C# with a generic if T
is the type from the parameter like so:
public void GenericMethod<T>(out Result result) where T : new(), BaseClass
{
T t = new T();
Handle(t, result);
}
private void Handle(BaseClass arg1, out Result result)
{
//do something need to be done for BaseClass;
}
For more information about C# and C++ generics you can take a look here
Upvotes: 1