C# 如何根据字符串内容运行命令,例如,输入字符串"Device"时,创建Device类的对象
时间: 2024-02-23 11:58:49 浏览: 20
可以使用反射来实现根据字符串内容运行命令。具体实现步骤如下:
1. 获取命令对应的类型,即"Device"对应的类类型。
```csharp
Type type = Type.GetType("命名空间.Device");
```
2. 判断类型是否存在,如果不存在则无法创建对象。
```csharp
if (type == null)
{
// 类型不存在,无法创建对象
return null;
}
```
3. 使用Activator.CreateInstance方法创建对象。
```csharp
object obj = Activator.CreateInstance(type);
```
4. 将对象转换为对应的类型。
```csharp
Device device = obj as Device;
```
完整代码如下:
```csharp
using System;
namespace 命名空间
{
public class Device
{
public void Start()
{
Console.WriteLine("Device started.");
}
}
class Program
{
static void Main(string[] args)
{
// 根据字符串内容创建对象
Type type = Type.GetType("命名空间.Device");
if (type == null)
{
Console.WriteLine("类型不存在。");
return;
}
object obj = Activator.CreateInstance(type);
Device device = obj as Device;
if (device != null)
{
device.Start();
}
}
}
}
```