4

Its been a while but i need to convert some custom code into C# (i think it was called emeralds or something somebody else gave to me). there is a certain method that takes a class(any class without any object conversions). this is the code im trying to convert.

      class  management
        Accessor current_class
        Accessor class_Stack

      def call(next_class)          #method, called global, takes a "class" instead 
                                       #of a variable, kinda odd
        stack.push(current_class)      #stack handling
        current_class = next_class.new #makes a new instance of specified next_class

      end
    end

next_class seems to be any class related to a base class and assigns a new instance of them to a variable called currentClass. there are other "methods" that do something similar. I've tried setting the parameter type to "object", but loses all the the "next_class" attributes that are needed. this is my attempt at it

     public class management {
        public Stack stack;           
        public Someclass currentClass; 

      public void Call(object nextClass) {
        stack.push(currentClass);   // stack handling    
        currentClass = new nextClass(); // conversion exception, otherwise loss of type

    }
    }

IS this even possible in C# another thing this language seems to able to keep attributes(methods too) from Child classes when you cast them as a base class. e.g cast green bikes as just bikes but it will still be green

can somebody point me in the right direction here? or do i need to rewrite it and change the way it does things?

4

1 回答 1

7

您想要的是泛型,我也认为,基于您将方法称为接口的事实。

因此,您的接口将定义“新”,并且类将从接口继承。

然后,您可以将该类作为泛型传递并在其上调用“new”的接口方法。

所以;

public interface IMyInterface
{
  void newMethod();
}

public class MyClass1 : IMyInterface
{
    public void newMethod()
    {
      //Do what the method says it will do.
    }
}

public class Class1
{
    public Class1()
    {
        MyClass1 classToSend = new MyClass1();
        test<IMyInterface>(classToSend);
    }

    public void test<T>(T MyClass) where T : IMyInterface
    {
        MyClass.newMethod();
    }
}

编辑

并查看 C# 4.0 中的“动态”。我这样说是因为如果您直到运行时才知道该方法是什么,您可以将其定义为动态的,并且您基本上是在告诉编译器“相信我,该方法将在那里”。

这是在你不能使用泛型的情况下,因为你调用的方法对于每个类都是不同的。

于 2013-04-24T05:30:13.567 回答