我试图根据给定的输入生成子类的实例,因此我创建了一个以 System.Type 作为键的字典(尽管我将使用字符串创建一个示例以便于理解)并返回 System.Type 。输入一个值。
像这样的东西:
Dictionary<string, System.Type> types = new Dictionary<string, System.Type>()
{
{ "Weapon", System.Type.GetType("WeaponClass") },
{ "Consumable", System.Type.GetType("ConsumableClass") },
{ "Resource", System.Type.GetType("ResourceClass") }
};
Run Code Online (Sandbox Code Playgroud)
WeaponClass、ConsumableClass和ResourceClass是同一类 的子类ItemClass。
所以我想创建一个函数来执行如下操作:
public ItemClass CreateItem(string itemName)
{
System.Type type = types[itemName];
// This is the part that I don't know how to make
return new type();
}
Run Code Online (Sandbox Code Playgroud)
这应该返回相应子类的实例,但我不知道该怎么做。
谁能帮我吗?
您可以使用Activator.CreateInstance创建特定类型的新对象:
var type = types[itemName];
var item = Activator.CreateInstance(type);
Run Code Online (Sandbox Code Playgroud)
但是,我建议采取稍微不同的方法。不要使用包含类型的字典,而是将其设为Func提供实际类型的列表。它是类型安全的并且具有编译时安全性。例如:
var types = new Dictionary<string, Func<ItemClass>>()
{
{ "Weapon", () => new WeaponClass() },
{ "Consumable", () => new ConsumableClass() },
{ "Resource", () => new ResourceClass() }
};
Run Code Online (Sandbox Code Playgroud)
现在你的方法可以是:
public ItemClass CreateItem(string itemName)
{
if(types.TryGetValue(nameOfType, out var factory))
{
return factory();
}
throw new Exception("Er, no idea what that type is");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
775 次 |
| 最近记录: |