C#反射,从字符串创建实例 [英] C# Reflection, Creating Instance from string

查看:83
本文介绍了C#反射,从字符串创建实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多表单...而且我还有一个字符串,其中包含必须为Show ...的Form名称.
例如...我有TObjectForm和ApplianceForm
和字符串str ="ApplianceForm"
我需要使用包含必须打开的表单名称的字符串来创建此表单...
我用这个...

I have many Forms...and also I have a string that contain name of Form that must be Show...
for Example...I have TObjectForm and ApplianceForm
and string str = "ApplianceForm"
I need to create this form using this string that contain name of form that must be opened...
I use this...

Type type = Type.GetType(typeName);
Form item = (Form)Activator.CreateInstance(type);



但这是错误ArgumentNullException ...但是我的字符串-> typeName例如是"ApplianceForm" ...但它是错误的...



but it is error ArgumentNullException...but my string -> typeName is for example "ApplianceForm"...but it is error...

推荐答案

string formTypeFullName = string.Format("{0}.{1}", this.GetType().Namespace, typeName);
Type type = Type.GetType(formTypeFullName, true);
Form item = (Form)Activator.CreateInstance(type);
item.ShowDialog();



类型名称需要这样的全名-> HouseDataBase.TObjectForm



type name need full name like this -> HouseDataBase.TObjectForm


您可以使用此:

You can use this:

object oform;
oform = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("
[namespace].[formname]");
((Form)oform).Show();



将该名称空间替换为您的应用程序/表单名称空间,并将[formname]替换为您的表单名称.



replace the namespace with your application/form namespace and [formname] with the name of your form.


这篇关于C#反射,从字符串创建实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆