我想创建一个在继承范例中保存不同对象的数组。我有一个 item 类,该类还可以继承其他几个类。我的目标是将继承 item 的不同对象放入数组中。我不知道对象的类型,因此需要实例化未知类型的对象。
我一直在关注这个Stackoverflow问题:Dynamically create an object of < Type>及其不同的变化。
using System;
const int _size= 3;
private Item[] _slots = new Item[_size];
// Method to place objects in array
// item here may be Carrot or Potato or another object
public void AddToBackpack(Item item) {
// Dynamically create Item object
var newItem = GetInstance<Item>(item.ToString());
// Find object in _slots array of similar type and merge newItem with it.
}
public T GetInstance<T>(string type) {
return (T)Activator.CreateInstance(Type.GetType(type));
}
// Classes
public class Carrot : Item {
public Carrot() {
_stackLimit = 5;
}
}
public class Potato : Item {
public Potato() {
_stackLimit = 3;
}
}
public abstract class Item {
public int _stackLimit { get; set; } = 1;
public int _stackSize { get; set; } = 1;
}
这是我尝试致电Activator.CreateInstance时遇到的错误
Run-time exception (line -1): Request failed.
Stack Trace:
[System.Security.SecurityException: Request failed.]
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at Submission#0.GetInstance[T](String type)
at Submission#0.<<Initialize>>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.CodeAnalysis.Scripting.ScriptExecutionState.<RunSubmissionsAsync>d__9`1.MoveNext()
答案 0 :(得分:0)
我不确定您为什么在这里使用反射。也许我不理解您的用例,但是,您正在传递Item item
是Carrot
还是Potato
,然后又想使用反射来创建相同的对象……为什么要做不使用传递的实例?
但是要解决您的问题,请尝试:
// change this method like this
public void AddToBackpack(Item item) {
// Dynamically create Item object
var newItem = GetInstance<Item>(item.GetType());
// Find object in _slots array of similar type and merge newItem with it.
}
// and this method like this
public T GetInstance<T>(Type type) {
return (T)Activator.CreateInstance(type);
}
或使其更通用
// change this method like this
public void AddToBackpack<T>(T item) where T: Item
{
// Dynamically create Item object
var newItem = GetInstance<T>();
// Find object in _slots array of similar type and merge newItem with it.
}
// and this method like this
public T GetInstance<T>() {
return (T)Activator.CreateInstance<T>();
}