0

im trying to write some kind a strongly typed routing system. Imagine ive got some class with method A that takes and returns string

public class SomeClass
{
    public string MethodA(string str)
    {
        return string.Format("SomeClass :: MethodA {0}", str);
    }
}

And I want my main method to look like this

class Program
{
    static void Main(string[] args)
    {
        var col = new SomeCollection();
        col.Add<SomeClass>("url", c => c.MethodA("test")); //Bind MethodA to "url"
    }
}

So my questions are:

  1. What should be Add method signature?
  2. How can I invoke MethodA in SomeCollection?

I guess it'll be something like

public class SomeCollection
{
    public void Add<TController> (string url, Func<TController, string> exp)
    {
      // Add func to dictionary <url, funcs>
    }

    public void FindBestMatchAndExecute (Request request)
    {
       //Search url in collection and invoke it's method.
       //Method params we can extract from request.
    }
}
Egor
  • 36
  • 4

1 Answers1

0

First, I think you want add instances of classes to a collection, not the types. Otherwise, you will need to use reflection. If my assumption is correct, then instead of declaring Func<x,y,z,...> just employ Action to be able to call any method with any numbers of parameters.

Dictionary<object, Action> tempDictionary = new Dictionary<object, Action>();
SomeClass someClass = new SomeClass();
tempDictionary.Add(someClass, () => someClass.MethodA("test"));
tempDictionary.Single(q => q.Key == someClass).Value();

but if you need return values, you will have to use Func instead of Action;

Dictionary<object, Func<string>> tempDictionary = new Dictionary<object, Func<string>>();
SomeClass someClass = new SomeClass();
tempDictionary.Add(someClass, () => someClass.MethodA("test"));
string temp = tempDictionary.Single(q => q.Key == someClass).Value();
daryal
  • 14,643
  • 4
  • 38
  • 54
  • Actually, im trying to write some kind a strongly typed routing system. So i dont have instances in moment im binding urls to methods of different classes. – Egor Jan 21 '13 at 12:10