我要写的一个程序里面有一个List程序类似如下:interface IChar;
{
....
}class A:person
{
...
}class B:person
{
...
}class C:person
{
...
}class D:person
{
...
}List<IChar> char= new List<IChar>();
如上所示...
IChar是公用的接口,ABCD都实现这个接口...我希望这个List<IChar>在创建的时候能够通过我输入的一个字符串数组来实现动态的加载
比如我输入的字符串数组是{B,C}...那么这个char就只加载B,C这两个类的对象...请问各位大虾如何实现???
我看的很多地方说什么用反射...
但是反射的机制我看得是云里雾里的...请各位不吝赐教
{
....
}class A:person
{
...
}class B:person
{
...
}class C:person
{
...
}class D:person
{
...
}List<IChar> char= new List<IChar>();
如上所示...
IChar是公用的接口,ABCD都实现这个接口...我希望这个List<IChar>在创建的时候能够通过我输入的一个字符串数组来实现动态的加载
比如我输入的字符串数组是{B,C}...那么这个char就只加载B,C这两个类的对象...请问各位大虾如何实现???
我看的很多地方说什么用反射...
但是反射的机制我看得是云里雾里的...请各位不吝赐教
xx為你說輸入的類名。
這就是反射,簡單不?
string s="A";
Type type = typeof(s);
type 不是System.String么?
这样就能创建你指定的类名的对象。
你參考下
Type type = typeof(test);
foreach (Object att in type.GetCustomAttributes(true))
{
attributeTest attribute = att as attributeTest;
if (attribute != null)
{
listBox1.Items.Add(attribute.m_str);
}
} foreach (MethodInfo att in type.GetMethods())
{
foreach (Object akk in att.GetCustomAttributes(true))
{
attributeTest attribute = akk as attributeTest;
if (attribute != null)
{
listBox1.Items.Add(attribute.m_str);
}
}
}
如果A,B,C,D都与执行代码同一个程序集.则可以这样调用
System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("命名空间.类名", false);
如:
object o = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("MyNameSpace.A", false);不同程序集的话.则要装载调用.如下:
System.Reflection.Assembly.Load("程序集名称").CreateInstance("命名空间.类名", false);
如:
object o = System.Reflection.Assembly.Load("MyDll").CreateInstance("MyNameSpace.A", false);
动态创建后再将o强制转换为IChar接口,如下:
IChar ichar = o as IChar;如果转换失败则ichar为null值.这样楼主明白了吧?
还是八楼比较正确...光类名没用,还要写上命名空间才能识别出来...
的确是Activator.CreateInstance(Type.GetType("你的类名"))
object o = Activator.CreateInstance(Type.GetType("你的类名")) ;
虽然创建了实例,但是还是装箱在obj,不拆箱还是不能用啊
比如
Person p = new Person();
p.Name = "张三";//这个ok大家都知道。
object o = Activator.CreateInstance(Type.GetType("Person")) ;
o.Name = "张三";//编译不能通过。
楼主的意思明显是怎么样在已知
string s = "Person";
的情况下,通过
object o = 某种办法(s);
或者
s.某种方法(某种参数);
获取到一个可以
o.Name = "张三";
的o。