动态生成某个类的实例,并调用该类的方法

land_L 2014-12-25 02:40:09
现有一组类class a,b,c....都实现了一个方法getData()

要求实现一个方法void work(string className),能够根据传入的className动态的生成该类的实例,并调用该类的getData方法

比如,我调用的时候是work("a")

那么work方法内的效果等同于:
a classA=new a();
a.getData();

求解该如何实现?
...全文
67 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
land_L 2014-12-25
  • 打赏
  • 举报
回复
搞定,多谢各位!
tcmakebest 2014-12-25
  • 打赏
  • 举报
回复
类名必须是包含空间的全名, 请看示例
CreateAndDo("CSDemo.ttt", "getData");
private void CreateAndDo(string classfullname, string methodname)
{
    Type t = Type.GetType(classfullname);
    if (t != null)
    {
        object val = Activator.CreateInstance(t);
        MethodInfo method = t.GetMethod(methodname);
        if (method != null)
        {
            method.Invoke(val, new object[] { });
        }
    }
}
public class ttt
{
    public void getData()
    {
        Debug.WriteLine("getdate");
    }
}
ajaxfeifei 2014-12-25
  • 打赏
  • 举报
回复

            dynamic ss = Activator.CreateInstance("dll名称", "classname");
            ss.getData();
如果实现了接口:

var ss = Activator.CreateInstance("dll名称", "classname") as IGetData;
ss.getData();
最后如果都不明白,就看http://blog.csdn.net/tonglian/article/details/2271066
於黾 2014-12-25
  • 打赏
  • 举报
回复
搜一搜:反射 只要知道命名空间,类名,属性名,函数名,都是可以通过反射调用的 可以实例化,也可以赋值,取值或执行函数

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧