如何使用反射创建按钮?

时间:2013-11-16 20:23:14

标签: c# .net reflection .net-assembly

我想从GAC dll创建任何实例,但不知道如何加载?

Assembly asemb = Assembly.LoadFile(dllName);
try
{
    obj = Activator.CreateInstance(asemb.GetType(type));
}
catch (Exception)
{
    return null;
}

我尝试使用此代码,但它不起作用

1 个答案:

答案 0 :(得分:1)

适合我:

var assembly = Assembly.Load("System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
var type     = assembly.GetType("System.Windows.Forms.Button");
var button   = Activator.CreateInstance(type);

从.dll文件中获取完整的程序集名称:

var assemblyFileName = @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\System.Windows.Forms.dll";
var assembly         = Assembly.LoadFile(assemblyFileName);
var assemblyName     = assembly.GetName().ToString();