exe在 D盘,要加载的程序集在 D:\Controls\这里 (包含BaseUserControl,和子类,也是 UserControl)我仅仅知道父 BaseUserControl 的名字,子类的名字不知道),我想动态的把这些子类Control加进来,并且转成 BaseUserControl代码如下:
string filePath = @"e:\Controls";
foreach(string fileName in Directory.GetFiles(filePath))
{
if (fileName.ToUpper().Contains(".DLL"))
{
Assembly _A = Assembly.LoadFrom(fileName);
Type[] types = _A.GetTypes(); //这里可以得到dll 里面所有的类
foreach (Type t in types)
{ //下面这行出错
//BaseUserControl b = (BaseUserControl)Activator.CreateInstance(t);
//改成 UserControl 就正确了 ,但是,无法取得其中的方法和属性
UserControl b = (UserControl )Activator.CreateInstance
this.panelContainer.Controls.Add(b);
b.Dock = DockStyle.Top;
}
}
}
// 这里无法转型
private void buttonApply_Click(object sender, EventArgs e)
{
foreach (UserControl u in this.panelContainer.Controls)
{
BaseUserControl r = (u as BaseUserControl); //此时的 r =null ,所以,无法使用Selected属性
if (r.Selected == true)
{
r.SetDataProvider(data);
r.Apply();
}
}
}
请问如何解决? 我 exe引用的文件 也是 D:\Controls\
string filePath = @"e:\Controls";
foreach(string fileName in Directory.GetFiles(filePath))
{
if (fileName.ToUpper().Contains(".DLL"))
{
Assembly _A = Assembly.LoadFrom(fileName);
Type[] types = _A.GetTypes(); //这里可以得到dll 里面所有的类
foreach (Type t in types)
{ //下面这行出错
//BaseUserControl b = (BaseUserControl)Activator.CreateInstance(t);
//改成 UserControl 就正确了 ,但是,无法取得其中的方法和属性
UserControl b = (UserControl )Activator.CreateInstance
this.panelContainer.Controls.Add(b);
b.Dock = DockStyle.Top;
}
}
}
// 这里无法转型
private void buttonApply_Click(object sender, EventArgs e)
{
foreach (UserControl u in this.panelContainer.Controls)
{
BaseUserControl r = (u as BaseUserControl); //此时的 r =null ,所以,无法使用Selected属性
if (r.Selected == true)
{
r.SetDataProvider(data);
r.Apply();
}
}
}
请问如何解决? 我 exe引用的文件 也是 D:\Controls\
1、UserControl b = (UserControl )Activator.CreateInstance
你确定每一个都是UserControl ?
最好用 as 转换!
2、 BaseUserControl r = (u as BaseUserControl); //此时的 r =null ,所以,无法使用Selected属性
if (r.Selected == true)
你确定每个BaseUserControl 都有Selected 属性?至少要加一个非空判断
if (r!=null && r.Selected == true)
可以确定,每一个子类都实现了 BaseUserControl中的方法。 这么说吧,D:\Controls这里面放的都是
BaseUserControl 的子类
UserControl b = (UserControl )Activator.CreateInstance
BaseUserControl b = b as BaseUserControl;这样会错误吗?我以前的代码:
Type type = Type.GetType("*********************************");
if (type != null)
{
// 创建的都是Form的子类。但是可以转换成基类的。
Form NormalFrm = (Form)Activator.CreateInstance(type);
if (NormalFrm != null)
{
NormalFrm.MdiParent = this;
NormalFrm.Show();
}
}
http://topic.csdn.net/u/20080806/11/aa416b26-500d-4bd0-ba0e-e1c506809cc0.html
其中 英文的一段 即可解决此问题!
1. In your Class1 project add reference to IBSBase.dll2. In your project that Activator.CreateInstance(), add reference to IBSBase.dll.3. Then it is ok to cast: BusinessRules.IBSBase rules = (BusinessRules.IBSBase)Activator.CreateInstance(obj);