Create a new instance of a subclass when I don't want to know the name of it
(I'm pretty new to C# so bear with me, started 2 days ago)
Ok, her开发者_如何转开发e is the general structure and idea
namespace Tokenize{
abstract class Token{
public Base(object id){
this.id = id;
}
private object id;
public object Id
{
get{...};
set{...};
}
public abstract object PerformOperation(object a, object b);
}
class NumberNine: Base{
public NumberNine(int num) : base(num){ }
public override int PerformOperation(int a, int b);
}
class LetterT: Base{
public LetterT(char letter) : base(letter){ }
public override string PerformOperation(string a, char b);
}
}
using Tokenize;
namespace Program{
class MyProg{
static void Main(string[] args)
{
Token token;
Stack stack;
//.....
//Read some input
string s = "T";
//.....
if(s==anonymousDerivedClassId){
//How do I come up with class LetterT and keep it anonymous?
Token token = new anonymousDerivedClass(); //
stack.Push(token)
}
//.....
//do some stuff
//.....
object a;
object b;
Token q = stack.Pop(token);
q.PerformOperation(a,b);
}
}
}
I want to create a new instance of a subclass where i don't want to know the name of it?
I "dont even know" if it exists?
Hopefully this wasn't too complicated...
EDIT:
I don't want to keep track of all the subclasses basically...
EDIT2 (New example):
Consider:
static void Main(string[] args)
{
Operator op;
string s = "*";
if(s==MulOperator.Identifier){
op = new MulOperator();
}
else{
op = new DivOperator();
}
perform(op);
}
static void perform(Operator op)
{
Console.WriteLine("Sum:{0}", op.PerformOperation(2.2,2.0));
}
Where I want to get rid of the new MulOperator()
and MulOperator.Identifier
with a more generic method of creating a subclass of in this case Operator
.
EDIT 3:*
(Solution) I'm going to try A Generic Factory in C#, it seems like that is what I want to achieve.
string s = "T";
string typeName = string.Empty;
// Determine whether s is a letter or digit
if (Char.IsDigit(s[0]))
{
typeName = "Digit" + s;
}
else if (Char.IsLetter(s[0]))
{
typeName = "Letter" + s;
}
// Get real type from typeName
Type type = Type.GetType(typeName);
// Create instance of type, using s as argument
object instance = Activator.CreateInstance(type, new object[] { s });
You'll have to edit your constructors so they take string s
as parameter, and do the proper validation and parsing.
精彩评论