If it's harder to explain using words, let's look at an example I have a generic function like this
void FunctionA<T>() where T : Form, new() { }
If I have a reflected type, how do I use it with the above function? I'm looking forward to do this
Type a = Type.GetType("System.Windows.Forms.Form"); FunctionA<a>();
Of cause the above method doesn't work.
Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.
The GetType method is inherited by all types that derive from Object. This means that, in addition to using your own language's comparison keyword, you can use the GetType method to determine the type of a particular object, as the following example shows.
GetType or Assembly. GetTypes method to get Type objects. If a type is in an assembly known to your program at compile time, it is more efficient to use typeof in C# or the GetType operator in Visual Basic. If typeName cannot be found, the call to the GetType(String) method returns null .
A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.
class Program { static void Main(string[] args) { int s = 38; var t = typeof(Foo); var m = t.GetMethod("Bar"); var g = m.MakeGenericMethod(s.GetType()); var foo = new Foo(); g.Invoke(foo, null); Console.ReadLine(); } } public class Foo { public void Bar<T>() { Console.WriteLine(typeof(T).ToString()); } }
it works dynamicaly and s can be of any type
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