I have a base class Number
that is inherited by classes One
, Two
and Three
.
I have a property
public Number SomeNumber{get;set;}
Initially, I have set SomeNumber
to either One
, Two
or Three
(Value Generated Randomly).
Later on, I want to set SomeNumber
to a new class of the same type of the old class. Is this possible? If so, how?
On initialization, SomeNumber
is set to One
Later on in the program, I want to set SomeNumber
to a new instance of One
.
I would add an abstract Method CreateInstance on the Number and implement it in all its concrete subclasses.
abstract class Number
{
abstract Number CreateInstance();
}
class One : Number
{
override Number CreateInstance()
{
return new One();
}
}
"later on"
Number newNumber = SomeNumber.CreateInstance();
It doesn't need reflection, is therefore typesafe and it would support arguments if the constructors would need some.
SomeNumber = (Number)Activator.CreateInstance(SomeNumber.GetType());
For parameters, you must box up the parameters as such:
public partial class Form1 : Form
{
public Number SomeNumber { get; set; }
public Form1()
{
InitializeComponent();
SomeNumber = new One();
SomeNumber = (Number)Activator.CreateInstance(SomeNumber.GetType(), new[] {1});
}
}
public class Number
{
}
public class One : Number
{
public One()
{
}
public One(Object a)
{
}
}
The post above by Stefan is a better method of implementing it. Another option would be to create an object factory
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.