实例化动态类



我想创建一个在继承范式中保存不同对象的数组。我有一个 item 类,可以继承其他几个类。我的目标是将继承 item 的不同对象放入数组中。我不知道对象的类型,因此需要实例化未知类型的对象。

我一直在关注这个stackoverflow问题:动态创建一个&lt的对象;类型>及其不同的变体。

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()

我不确定为什么在这里使用反射。也许我不了解您的用例,但是,您正在传递Item item什么是CarrotPotato,然后您想使用反射创建相同的对象...为什么您不使用经过的实例?

但是要解决您的问题:

// 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>(); 
}

最新更新