c# - 在不使用 new 关键字的情况下在 C# 中创建对象?

标签 c# new-operator

<分区>

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

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

最佳答案

您可以使用 Activator class .

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

关于c# - 在不使用 new 关键字的情况下在 C# 中创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8049193/

相关文章:

c++ - 将 malloc 更改为新的运算符

c++ - memmove、memcpy 和新的

c# - 在 JsonSerializerSettings 中将 null 更改为空

c# - 恢复 Nuget 包缓存?

c# - 运行 Visual Web Developer 2008 Express 时出错

c++ - 哪个 new 运算符将被称为 new 或 new[]?

c++ - 重载运算符的线程安全新

c# - 快速linq计数问题

c# - "run text"标记在 XAML 中意味着什么?

c++ - 当我在动态数组 (C++) 中使用变量时,它似乎被取消引用