Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force others to obey a specific layout for a child class?

Tags:

c#

oop

reflection

I have an abstract class as follows:

public abstract class Node
{
    public abstract void run();
}

There are some child nodes that may have several properties as input and output. But all the operation is done just in run() method that each Node should implement. For example a Node that draws a line could be something like this:

public class LineNode : Node
{
    [Input]
    public Point a;
    [Input]
    public Point b;
    [Output]
    public Line line;
    public override void run()
    {
        line = new Line(a, b);
        // draw line ...
    }
}

[AttributeUsage(AttributeTargets.Field)]
public class Input : System.Attribute
{

}
[AttributeUsage(AttributeTargets.Field)]
public class Output : System.Attribute
{

}

As you see I don't have any prior information about fields in the child classes. ** For a Node to be a valid node in convention, It is just required to have at least one output.** I want to force all other users to have at least one output in their Nodes so I can find it by reflection by looking for a field that [Output] attribute is applied to.
Is this possible?
And if this is, Is it the best way?

Thanks for any help


Here the same issue raised but the suggested solution settled it in the run time. I was looking for an Object Oriented solution though. Which one is more logical actually?

like image 480
a.toraby Avatar asked Jun 08 '15 14:06

a.toraby


1 Answers

You could do something like this

public interface IRunnable<T>
{
    T Run();
}

And then every class that implements this interface must provide this run method and return a (strongly typed ) result.

Or if the run method does not return the result

public interface IRunnable<T>
{
    void Run();
    T Value {get;}
}
public class LineNode : IRunnable<Line>
{
    [Input]
    public Point a;
    [Input]
    public Point b;

    private Line line;
    public Line Value { get{return line;}}
    public override void run()
    {
    line = new Line(a, b);
    // draw line ...
    }

}

like image 102
George Vovos Avatar answered Sep 27 '22 17:09

George Vovos