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"
}
}
所以我的问题是:
我猜它会像
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.
}
}
答案 0 :(得分: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();