在 C# 中创建一个对象而不使用 new 关键字? [英] Create a object in C# without the use of new Keyword?

查看:332
本文介绍了在 C# 中创建一个对象而不使用 new 关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 C# 中不使用 new 关键字来创建一个对象,比如 class.forname();在 Java 中.

Is there a way to create a object without the use of new keyword in C# some thing like class.forname(); in java.

我想动态创建一个类的对象.对象创建可能取决于用户输入.
我有一个基类 x,它有 5 个子类(a、b、c、d、e).我的用户输入将是 a 或 b 或...e 类名.使用它,我需要创建该类的对象.我该怎么做

I want to dynamically create a object of a class. The object creation may depend on the users input.
I have a base class x and there are 5 subclasses (a,b,c,d,e) of it. My user input will be a or b or...e class names. Using this I need to create a object of that class.How do I do this

推荐答案

您可以使用 激活器类.

Type type = typeof(MyClass);
object[] parameters = new object[]{1, "hello", "world" };
object obj = Activator.CreateInstance(type, parameters);
MyClass myClass = obj as MyClass;

这篇关于在 C# 中创建一个对象而不使用 new 关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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