0

ある種の厳密に型指定されたルーティング システムを作成しようとしています。文字列を受け取って返すメソッド A を持つクラスがあると想像してください

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

そして、メインメソッドを次のようにしたい

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

だから私の質問は:

  1. メソッド署名を追加する必要がありますか?
  2. SomeCollection で MethodA を呼び出すにはどうすればよいですか?

みたいな感じになると思います

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.
    }
}
4

1 に答える 1

0

まず、型ではなく、クラスのインスタンスをコレクションに追加する必要があると思います。それ以外の場合は、リフレクションを使用する必要があります。私の仮定が正しければ、宣言する代わりに、任意の数のパラメーターで任意のメソッドを呼び出すことができるようにするFunc<x,y,z,...>だけです。Action

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();

ただし、戻り値が必要な場合は、Func代わりに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();
于 2013-01-21T11:55:08.693 に答える