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?
What you want is Generics and I think also, based on the fact that you call a method, Interfaces.
So your Interface will define "new" and the Class will inherit from the interface.
You can then pass the class as a generic and call the Interface method of "new" on it.
So;
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();
}
}
EDIT
And check out "dynamic" in C# 4.0. I say this because if you don't know what the method is until runtime you can define it as dynamic and you are basically telling the compiler that "trust me the method will be there".
This is in case you can't use generics because the methods you call will be different for each class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With