问题描述
我已经看到了这个主题:
I've seen this Topic : Creating an instance from a class name
和编写代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
object obj = Activator.CreateInstance(null, "MyClass");
MyClass t = (MyClass)obj;
t.My1 = 100;
MessageBox.Show(t.My1.ToString());
}
}
public class MyClass
{
public int My1 { get; set; }
public int My2 { get; set; }
}
然而,当它运行有一个例外:
However when its runs there's an exception:
Could not load type 'MyClass' from assembly 'Test_Reflection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
我还有一个问题。我有一个具有某些属性一个程序集的类。在另一个组装我想创建它的实例,并可以访问它的属性,只要使用弦类的名称输入其中之一。我该怎么做?
I have another question. I have a class in one assembly that has some property. In another assembly I want create instance of it and get access to it's properties, by typing one of them just using stringy Class Name. How can I do that?
推荐答案
据的 空
其实并不意味着的当前装配的。这意味着装配将被搜索(其无论何时你的类位于另一个组件)。还需要指定不仅类名。因此,为了防止搜索并获得正确输入你需要写完整的集限定名称一>:
According to MSDN null
actually doesn't mean current assembly. It means that assembly will be searched (its matter when your class is located in another assembly). Also you need specify not only the class name. So, to prevent searching and get type correctly you need to write full assembly-qualified name:
Type objType = Type.GetType("YourNamespace.MyClass, YourAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
object obj = Activator.CreateInstance(objType);
MyClass t = (MyClass)obj;
您可以检索例如用下面的代码(检查你是不是弄错)大会限定的名称
Assembly-qualified name you can retrieve for example with next code (to check that you are not mistaken):
string name = typeof(MyClass).AssemblyQualifiedName;
这篇关于如何在给定的类名称的类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!