当我不想知道它的名称时,创建一个子类的新实例

时间:2011-04-26 14:35:41

标签: c# inheritance polymorphism tokenize

(我对C#很新,所以请耐心等我,2天前开始)

好的,这是一般结构和想法

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

         }
    }
}

我想创建一个子类的新实例,其中不希望知道它的名称?

我“甚至不知道”它是否存在?

希望这不是太复杂......

修改

我不想基本上跟踪所有子类...

EDIT2(新示例):

考虑:

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

我希望摆脱new MulOperator()MulOperator.Identifier,使用更通用的方法创建本例Operator的子类。

编辑3:*

(溶液) 我要试试A Generic Factory in C#, 看起来这就是我想要实现的目标。

1 个答案:

答案 0 :(得分:3)

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

您必须编辑构造函数,以便将string s作为参数,并进行正确的验证和解析。