[英]Create new class instance / reset class instance of a class instance that is inherited from an abstact base class
Prior I'd like to appologize for the long title but I didn't figure out a shorter version. 在此之前,我想为长标题表示歉意,但我没有找到一个简短的标题。
I have an abstract base class that delivers generic methods to access functions in test classes, that derive from my base class. 我有一个抽象基类,它提供了通用方法来访问从我的基类派生的测试类中的函数。
I have a collection of classes that itself have a reference to those test classes. 我有一些类的集合,这些类本身具有对这些测试类的引用。
The struct is: 结构为:
// A really simplified example for my manager
Collection<AbstractBaseClass> Manager = new Collection<AbstractBaseClass>
{
TestClassA();
TestClassB();
}
Now I come to the point that I need to kill and recreate the instance in the collection of the testclass without knowledge of which testclass is in this collection. 现在,我要指出的是,我需要在不知道该测试集中的哪个测试类的情况下,在测试类的集合中终止并重新创建实例。
I try to do sth. 我尝试做某事。 like (pseudocode) 像(伪代码)
Manager[0] = null;
Manager[0] = new (object)Manager[0].GetType();
I already stumbled over Get a new object instance from a Type but this - however - doesn't work because CreateInstance is no member of System.Activator . 我已经迷迷糊糊地从Type中获取一个新的对象实例,但是-这是行不通的,因为CreateInstance不是System.Activator的成员 。 Also I cannot find the ObjectType class. 我也找不到ObjectType类。
Long explaination, short question: How can I create a new instance from a class where I only have an Instance? 长解释,短问题:如何从只有一个实例的类中创建一个新实例?
Thank you very much, ADP. 非常感谢您,ADP。
如果您知道所有类都有一个公共的无参数构造函数,则可以执行以下操作:
manager[i] = (AbstractBaseClass)Activator.CreateInstance(manager[i].GetType());
While you could use Activator.CreateInstance
to create instances from a given type, maybe you can solve this in a more optimal way using generics : 虽然可以使用Activator.CreateInstance
从给定类型创建实例,但是也许可以使用泛型以更优化的方式解决此问题:
public sealed class TestCollection<T> : ICollection<T>
where T : AbstractBaseClass, new()
{
private List<T> Tests { get; } = new List<T>();
public T this[int index] => Tests[index];
public void Add(T test) => Tests.Add(test);
// Rest of ICollection<T> members
public void NewAt(int testIndex) => Tests[testIndex].Insert(testIndex, new T());
}
Now you don't need reflection anymore, because T
must be a class with a public, paramaterless constructor : 现在您不再需要反射 , 因为T
必须是具有公共,无参数构造函数的类 :
TestCollection<AbstractBaseClass> manager = new TestCollection<AbstractBaseClass>();
manager.Add(new Test());
manager.Add(new Test());
manager.Add(new Test());
manager.NewAt(1);
Now you've already created a new instance of Test
without reflection on index 1
and you can still access the new object typed as Test
using the TestCollectin<T>
indexer: manager[1]
. 现在,您已经创建了一个Test
的新实例,但没有在索引1
上产生反射,您仍然可以使用TestCollectin<T>
索引器: manager[1]
访问类型为Test
的新对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.