C#反射:实例化字符串类名称的对象 [英] C# Reflection: Instantiate an object with string class name

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

问题描述

我的情况是下一个:我用Visual C#2010工作发展明示Windows窗体应用程序。当用户登录时,dinamically建立与数据库表中加载选项的MenuStrip。在该表中保存我的id,选项名称和表单名称。

my situation is the next: I'm working with Visual C# 2010 express developing a Windows Forms Application. When the user logins, dinamically build a menustrip with options loaded from a database table. In that table i save id, option name and Form Name.

因此​​,假设在我的项目,我有一个名为Contabilidad形式,它具有Contabilidad.cs那就是主类,所以如果我想创建一个新的形式表现出来我这样做:

So, suppose that in my project i have a Form named Contabilidad, it has Contabilidad.cs that is the main class , so if i wanna create a new form and show it i do this:

Contabilidad frmConta = new Contabilidad();
frmConta.Show();



但是,在这种情况下,因为菜单选项存储在数据库中,在数据库中我只有字符串Contabilidad。所以,我想用C#反射创建Contabilidad或任何其他形式的只能与字符串格式的类名称的实例

But in this case, because the menu options are stored in database, in database i only have the string "Contabilidad". So, i want to use C# reflection to create a instance of Contabilidad or any other form only with class name in string format.

首先我想这:

Form frmConta= (Form)Activator.CreateInstance(null, "Contabilidad").Unwrap();

由于我在StackOverflow的问题阅读,如果我使用空我指的是当前组件(我形式都是在同一个项目),但我得到这个消息:

Because i read in a StackOverflow question that if i use null i'm referring to current assembly (my forms are all in the same project), but i get this message:

Could not load type 'Contabilidad' from assembly 'AccountingSA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

的类定义是下一个:

namespace AccountingSA {
public partial class Contabilidad : Form
{
    public Contabilidad()
    {
        InitializeComponent();
    } ...



另外我想这:

Also i tried this:

Assembly assembly = Assembly.Load("AccountingSA");
Type t = assembly.GetType("Contabilidad");
Form frmConta = (Form)Activator.CreateInstance(t);



但我得到ArgumentNullException此消息:

But i get ArgumentNullException with this message:

Value cannot be null. Parameter name: type

由于变量t为空

什么,我做错了什么? 。在此先感谢

What i'm do wrong? Thanks in advance.

推荐答案

使用该类型的完全限定名称:

Use the fully-qualified name of the type:

Type t = assembly.GetType("AccountingSA.Contabilidad");



从的 Assembly.GetType(串)

名称类型:System
类型的全名。
[...]这个名字参数包括命名空间,但不大会。

name Type: System.String The full name of the type. [...] The name parameter includes the namespace but not the assembly.

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

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