c# - 如何创建类型声明的实例?
问题描述
我想将一个类声明存储在一个结构中,然后从该类实例化新对象,但我遇到了一些障碍。我知道如何用其他几种语言做到这一点,但在 C# 中我还没有取得任何成功。
abstract class Command
{
// Base class for all concrete command classes.
}
class FooCommand : Command
{
}
class ListCommand : Command
{
}
现在我想要一个存储一些数据的结构和一个 Command 子类类 ref:
struct CommandVO
{
string trigger;
string category;
Type commandClass;
}
稍后在其他地方我想从字典中获取 VO 结构并创建具体的命令对象:
var commandMap = new Dictionary<string, CommandVO?>(100);
commandMap.Add("foo", new CommandVO
{
trigger = "foo", category = "foo commands", commandClass = FooCommand
});
commandMap.Add("list", new CommandVO
{
trigger = "list", category = "list commands", commandClass = ListCommand
});
...
var commandVO = commandMap["foo"];
if (commandVO != null)
{
var commandClass = commandVO.Value.commandClass;
// How to instantiate the commandClass to a FooCommand object here?
}
我已经在此页面上查看了有关如何实例化类型的方法,但由于Type
不代表任何具体的类,我想知道如何commandClass
实例化为其类型的正确对象?在这种情况下,将类声明存储Type
在结构中是否正确,还是有更好的方法?
解决方案
你必须用以下包装类型typeof()
:
var commandMap = new Dictionary<string, CommandVO?>(100);
commandMap.Add("foo", new CommandVO {
trigger = "foo", category = "foo commands", commandClass = typeof(FooCommand)
});
您可以像这样编写扩展方法:
internal static class CommandHelper {
internal static Command createCommand(this Dictionary<string, CommandVO?> d, string name) {
if (!d.ContainsKey(name)) return null;
return Activator.CreateInstance(d[name]?.commandClass) as Command;
}
}
比你能得到你的Cammand
实例:
var instance = commandMap.createCommand("foo");
推荐阅读
- jsp - 在 Jmeter/Loadrunner 中处理浏览器动态值
- encryption - 关于 DES-CBC 模式下加密的 RTP/RTCP 问题
- java - Android Java Retrofit URL 意外更改?
- javascript - 有没有办法使用 pdfjs 库保存自定义元数据
- javascript - 如何隐藏从 Django Web 应用程序发送的用户访问令牌?
- swift - 如果我使用多个“if 语句”然后在 swift 中出现错误(由于未捕获的异常而终止应用程序)
- flutter - Flutter - 灰色小部件区域,但仅适用于部分用户
- php - $_POST 输入未到达处理程序页面
- oauth-2.0 - Can "kid" in JWKS be just string of numbers, and what is the maximum number of characters kid can hold?
- reactjs - 如何使用 setInterval 每秒增加一个 React 状态?