First of all I really didn't know how to ask it properly. So forgive me for that. But I'll try to explain what is my problem.
I do have an abstract class where on the constructor I'm calling an abstract method declared on the very same class, and Im doing this because I do want to force all the derivated class to not just implement my abstract method but also call it (I think here is where the Template Method pattern comes in).
BTW: I know it is not the best approach to make sure all things will be correctly writen but due external problems I would like to minimize my future problems with bad implementation. The snippet is below:
public abstract class Generic
{
public Generic()
{
Console.WriteLine("This is the generic");
this.SetRules();
}
protected abstract void SetRules();
}
Well, on one of my derivated class need to set up a private variable on the declaration, and I would like to use this variable inside the overriden method. As I don't know how many possibilities I would need to each one of my derivated classes, I would like to declare it inside each one of my derivated class as necessary. An example below:
public class Derivated2 : Generic
{
private int _parameter;
public Derivated2(int parameter)
{
this._parameter = parameter;
}
protected override void SetRules()
{
int x = 0;
x = 1 + 3;
Console.WriteLine(String.Concat("This is the derivated2 with x: ", x, "; _parameter: ", _parameter));
}
}
Now to the problem;
When I'm calling my derivated2 class, I can't use/see my variable value specified on declaraion:
public static void Main()
{
Derivated2 _class1 = new Derivated2(2);
}
My output is:
This is the generic
This is the derivated2 one with x: 4; _parameter: 0
How can I see/use my variable on my overriden asbtract method? If I can't, What would be the best approach to reach my goal securing the SetRules method is going to be called no matter what the developer does and also can use private variables inside his derivated class?
Here is the full code I have done:
Calling SetRules on Abstract Generic Class
Calling SetRules on Derivated Class
Aucun commentaire:
Enregistrer un commentaire