Question
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?
Example:
On initialization, SomeNumber
is set to One
Later on in the prog开发者_如何学编程ram, 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
精彩评论