如何根据类名获取类的实例?
我看过这个主题:从类名创建实例
并编写了这段代码:
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; }
}
但是,当它运行时出现异常:
Could not load type 'MyClass' from assembly 'Test_Reflection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
我还有另一个问题。我在一个程序集中有一个具有某些属性的类。在另一个程序集中,我想创建它的实例并通过仅使用字符串类名称键入其中一个属性来访问它的属性。我怎样才能做到这一点?
I've seen this Topic : Creating an instance from a class name
and written this code:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需将名称空间添加到类名称前面即可。在控制台 exe 项目中,这对我有用。您使用返回的对象句柄的方式确实存在问题。它不是一个
Object
,而是一个ObjectHandle
,您需要调用Unwrap()
获取实际的类型实例。You just need to prepend the namespace to the class name. In a console exe project, this works for me. You did have a problem with the way you were using the returned object handle. It's not an
Object
, but anObjectHandle
and you need to callUnwrap()
get at the actual type instance.根据 MSDN
null
实际上并没有表示当前程序集。这意味着将搜索程序集(当您的类位于另一个程序集中时,这很重要)。此外,您不仅需要指定类名。因此,为了防止搜索并正确获取类型,您需要编写完整的 程序集-qualified name:程序集限定名称,您可以使用以下代码检索例如(以检查您是否弄错了):
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:Assembly-qualified name you can retrieve for example with next code (to check that you are not mistaken):