背景描述:
做个项目,一个解决方案里面有多个项目,项目1(类库)引用项目2(类库)、3(类库),则项目2中就不能引用项目1。但是项目2中需要调用项目1 中的一个窗体对象,并获取窗体对象中的一个public变量_SWhere,就想到了用一下反射。在此记录下来以免。也可能各位大神有更加简单的方法,欢迎告诉小弟。若有不对的地方,欢迎指正,及时更改。
假设:
程序运行目录为“C:\”,
项目1 这个编译出来的动态库名字叫1.dll,
项目1中的命名空间叫 Mynamespace,
项目1中需要被调用的窗体类叫FrmTest。
程序:
项目1中调用项目2中的窗体方法:
public virtual string GetSearchStr(IBllBase BLL)
{
Assembly assembly = Assembly.LoadFile("C:\\1.dll");
//获取对象
object obj1 = assembly.CreateInstance("Mynamespace.FrmTest");
//获取对象类型,其中BLL是FrmTest窗体构造函数的参数
Type mytype = obj1.GetType();
obj1 = mytype.Assembly.CreateInstance(mytype.FullName, true, BindingFlags.CreateInstance, null, new object[] { BLL }, CultureInfo.CurrentCulture, null);
//FrmTest窗体继承了XtraForm
XtraForm a = (obj1 as XtraForm);
try
{
a.ShowDialog();
if (a.DialogResult == DialogResult.OK)
{
//获取对象属性值
string s = GetObjectPropertyValue(a,mytype, "_SWhere");
return s;
}
else
{
return " ";
}
}
catch (System.Exception ex)
{
return " ";
}
finally
{
a.Dispose();
a = null;
obj1 = null;
assembly = null;
mytype = null;
}
}
关于CreateInstance函数,在微软官网上有讲解
关于函数GetObjectPropertyValue,我是参考了这篇文章:
https://www.cnblogs.com/rinack/p/5227111.html
我自己又按照我的情况改了改
public static string GetObjectPropertyValue(Object t,Type type, string propertyname)
{
PropertyInfo property = type.GetProperty(propertyname);
if (property == null)
{
return string.Empty;
}
object o = property.GetValue(t, null);
if (o == null)
{
return string.Empty;
}
return o.ToString();
}
注意,这个属性值在FrmTest的声明不能写成
public stirng _SWhere;
这样我发现是获取不到的,要改成:
public string _SWhere
{
get;
set;
}
这样就能调用项目1中的窗体了,并且获得了窗体类的一个属性值 _SWhere。