我要写的一个程序里面有一个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这两个类的对象...请问各位大虾如何实现???
我看的很多地方说什么用反射...
但是反射的机制我看得是云里雾里的...请各位不吝赐教

解决方案 »

  1.   

    Type type = typeof(xx);
    xx為你說輸入的類名。
    這就是反射,簡單不?
      

  2.   

    Type type = typeof(xx); 如果:
    string s="A";
    Type type = typeof(s);
    type 不是System.String么?
      

  3.   

    Activator.CreateInstance(Type.GetType("你的类名"))
    这样就能创建你指定的类名的对象。
      

  4.   

    下面是一個例子,test就是你所輸入的類名,下面是實現用反射列出test類中所有的屬性和方法名:
    你參考下
                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);
                        }
                    }
                }
      

  5.   

    上面的都是误人子弟!!字符串哪来真实的Type?反射动态创建对象:
    如果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值.这样楼主明白了吧?
      

  6.   

    呵呵,谢谢各位大虾了...PS:三楼:简单工厂不是需要switch..case么,好麻烦,呵呵...
    还是八楼比较正确...光类名没用,还要写上命名空间才能识别出来...
    的确是Activator.CreateInstance(Type.GetType("你的类名")) 
      

  7.   

    我看你们说的都不行,
    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。