它已经有一段时间但我需要将一些自定义代码转换为C#(我认为它被称为祖母绿或其他人给我的东西).有一种方法需要一个类(没有任何对象转换的任何类).这是我试图转换的代码.
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
Run Code Online (Sandbox Code Playgroud)
next_class似乎是与基类相关的任何类,并将它们的新实例分配给名为currentClass的变量.还有其他类似的"方法".我已经尝试将参数类型设置为"object",但是丢失了所有需要的"next_class"属性.这是我的尝试
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
}
}
Run Code Online (Sandbox Code Playgroud)
这在C#中甚至是可能的,当你将它们作为基类转换时,这种语言似乎能够保留Child类的属性(方法).例如,将绿色自行车当作自行车,但它仍然是绿色的
有人能指点我在这方向吗?或者我是否需要重写它并改变它的工作方式?
你想要的是泛型,我想也是基于你调用方法接口的事实.
所以你的接口将定义"new",Class将继承接口.
然后,您可以将该类作为泛型传递,并在其上调用"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();
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
并在C#4.0中查看"动态".我这样说是因为如果你不知道方法是什么,直到运行时你可以将它定义为动态,你基本上告诉编译器"相信我的方法会在那里".
这是因为你不能使用泛型,因为你调用的方法对于每个类都是不同的.