【问题标题】:Pass method into generic function and invoke it将方法传递给泛型函数并调用它
【发布时间】:2013-01-21 11:50:00
【问题描述】:

我正在尝试编写某种强类型路由系统。 想象一下,我有一个带有方法 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.
    }
}

【问题讨论】:

  • 问题是:你从哪里得到SomeClass 的实例应该被传递到 lambda 表达式中?
  • @defaultlocale: c 是 lambda 表达式的参数,就像 xSelect(x =&gt; x.Id) 中一样。
  • @DanielHilgarth,谢谢,实际上我误读了这个问题。
  • Add 的预期行为是什么?
  • 我更改了我原来的帖子,以便更容易弄清楚发生了什么)

标签: c# generics lambda


【解决方案1】:

首先,我认为您希望将类的实例添加到集合中,而不是类型。否则,您将需要使用反射。如果我的假设是正确的,那么不要声明Func&lt;x,y,z,...&gt;,而是使用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();

【讨论】:

  • 实际上,我正在尝试编写某种强类型路由系统。所以我在将 url 绑定到不同类的方法时没有实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多