For<T>()
- Hi
Im using a externa library with a function that I must call For<T>().
If I have a class:
public class Test
{}
Then I can do For<Test>()
My problem is that I only have objects of class Type like:
Type test2 = ...
I would like to use For<test2>() but its not possible...... how do I do this....???
//lasse
Lasse
Answers
- Use reflection. Call GetMethod on the library class to get the For method, then MakeGenericMethod to bind the type, and Invoke to invoke it.
class Customer { public string name; } class TheLib { public static void For<T>() { Console.WriteLine( typeof( T ).ToString() ); } } class Program { static void Main( string[] args ) { Type T = typeof( Customer ); Test( T ); } static void Test( Type T ) { MethodInfo unboundMethod = typeof( TheLib ).GetMethod( "For" ); MethodInfo boundMethod = unboundMethod.MakeGenericMethod( T ); boundMethod.Invoke( null, new object[] { } ); } }
- Proposed As Answer byShival Mathur Thursday, November 05, 2009 10:31 AM
- Marked As Answer byBin-ze ZhaoMSFT, ModeratorMonday, November 09, 2009 8:29 AM
All Replies
Hi,
I dont know if I have understood the problem correctly but you must pass the type to a template method. Passing objects is done through parameters.
Shival- Either make the Test class generic:
public class Test<T> { }
then inside the class, call the method typed:
For<typeof(T)>()
Another option (which I actually don't recommend) is to always pass the type object like this:
For<object>()
Geert van Horrik - CatenaLogic
Visit my blog: http://blog.catenalogic.com
Looking for a way to deploy your updates to all your clients? Try Updater! - I better show the complete code snippetI am picking all types from a Assembly matching a specific criteria.
IEnumerable<Type> ModelImpl = Assembly.GetTypes().Where(t => t.IsClass && t.Namespace.EndsWith("Model")); foreach (Type impl in ModelImpl) { config.For<????>().Add(); }
"config" is part of a library Im using so I cant change anything.
My problem is "?????",,,
Lasse - Use reflection. Call GetMethod on the library class to get the For method, then MakeGenericMethod to bind the type, and Invoke to invoke it.
class Customer { public string name; } class TheLib { public static void For<T>() { Console.WriteLine( typeof( T ).ToString() ); } } class Program { static void Main( string[] args ) { Type T = typeof( Customer ); Test( T ); } static void Test( Type T ) { MethodInfo unboundMethod = typeof( TheLib ).GetMethod( "For" ); MethodInfo boundMethod = unboundMethod.MakeGenericMethod( T ); boundMethod.Invoke( null, new object[] { } ); } }
- Proposed As Answer byShival Mathur Thursday, November 05, 2009 10:31 AM
- Marked As Answer byBin-ze ZhaoMSFT, ModeratorMonday, November 09, 2009 8:29 AM


