如何根据类名获取类的实例?

发布于 2024-10-21 21:25:11 字数 849 浏览 1 评论 0原文

我看过这个主题:从类名创建实例

并编写了这段代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不如归去 2024-10-28 21:25:12

您只需将名称空间添加到类名称前面即可。在控制台 exe 项目中,这对我有用。您使用返回的对象句柄的方式确实存在问题。它不是一个 Object,而是一个 ObjectHandle,您需要调用 Unwrap() 获取实际的类型实例。

namespace CSharpConsoleTest
{
    public class MyClass
    {
        public int My1 { get; set; }
        public int My2 { get; set; }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            var obj = Activator.CreateInstance(null, "CSharpConsoleTest.MyClass");

            var t = (MyClass)obj.Unwrap();
            t.My1 = 100;
            MessageBox.Show(t.My1.ToString());
        }
    }
}

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 an ObjectHandle and you need to call Unwrap() get at the actual type instance.

namespace CSharpConsoleTest
{
    public class MyClass
    {
        public int My1 { get; set; }
        public int My2 { get; set; }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            var obj = Activator.CreateInstance(null, "CSharpConsoleTest.MyClass");

            var t = (MyClass)obj.Unwrap();
            t.My1 = 100;
            MessageBox.Show(t.My1.ToString());
        }
    }
}
奈何桥上唱咆哮 2024-10-28 21:25:11

根据 MSDN null 实际上并没有表示当前程序集。这意味着将搜索程序集(当您的类位于另一个程序集中时,这很重要)。此外,您不仅需要指定类名。因此,为了防止搜索并正确获取类型,您需要编写完整的 程序集-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;

程序集限定名称,您可以使用以下代码检索例如(以检查您是否弄错了):

string name = typeof(MyClass).AssemblyQualifiedName;

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文