i like to know about how to instantiate generic object with reflection
pls find my example,
I want to create an Object of "hello" with generic type "ClassABC"
//want to Create hello object,with generic type will declare at run time only
public void DoHello(String ClassName)
{
Type TypeClassABC= Type.GetType(ClassName);
hello _hello= new hello
}
But get a build error:
the type or namespace "TypeClassABC" could not be found,
Bechir BejaouiPosted Sep 21, 2010, 5:55 AM
OK my freind here are two small techniques to make you hand on process.
using System;
using System.Collections.Generic;
using System.Reflection;
namespace TestProject01
{
class Program
{
static void Main(string[] args)
{
Type t = typeof(Hello<>);
Type[] generic = new Type[]{typeof(abc)};
Type genericT = t.MakeGenericType(generic);
//Technique 1
ConstructorInfo constructorInfo = genericT.GetConstructor(new Type[]{});
constructorInfo.Invoke(null);
//Technique 2
object obj = Activator.CreateInstance(genericT);
Console.Read();
}
}
class Hello
{
public Hello()
{
Console.WriteLine(string.Format("I'm {0}, my generic type is {1}",
this.GetType().ToString(),
typeof(T).ToString()));
}
}
class abc
{
}
}
But I advise you before stating developping using reflection to read some tutorial about it before
http://en.csharp-online.net/Attributes_and_Reflection%E2%80%94Reflection
I strongly advise you following this cours that I already followed in the past before taking action taward reflection
harshil ohPosted Sep 21, 2010, 1:25 AM
actulay iam looking for create generic class, its generic type will declare at run time via reflection,how its possible.
void CreatHelloObject()
{
//type is from one dll "sample.dll" , type name is 'abc'
hello<___> helloObj = new hello<___>(); .
}
public Class hello
{
}
Bechir BejaouiPosted Sep 20, 2010, 5:40 PM
Please take a look on that
http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx