【问题标题】:Making custom LINQ extension on dynamic type在动态类型上制作自定义 LINQ 扩展
【发布时间】:2012-07-24 22:14:47
【问题描述】:

我有以下代码:

dynamic users = BLClass.MYBLMethod();
List<string> usernames = BLClass.MYBLSecondMethod();
foreach (string username in usernames)
{
    users[username].test();
}

我正在从 BL 方法获取用户(动态类型)。接下来从其他方法我正在获取用户名列表。之后,我在用户名列表上应用 foreach。在这个循环中,我调用一个方法“测试”。这个“测试”方法将在我的 JavaScript 代码中使用。现在我的问题是如何将上面的代码转换成这样的扩展方法

BLClass.SomeExtensionMethod(methodname)

即我的 SomeExtensionMethod 将涵盖以下逻辑:

dynamic users = BLClass.MYBLMethod();
List<string> usernames = BLClass.MYBLSecondMethod();
foreach (string username in usernames)
{
    users[username].methodname();
}

你能帮我做这个扩展吗?

编辑:

我的目标是拥有 BLClass.SomeExtensionMethod(methodname) 。我将在其中传递方法名称,并且内部代码(在扩展内)应该调用此代码:

users[username].methodname();

【问题讨论】:

  • 我必须在多个地方使用此代码。最好为它做一个扩展。
  • 不太清楚自己想做什么。您要扩展哪种类型?你的代码示例都是一样的!
  • 我想做自定义扩展“BLClass.SomeExtensionMethod().test()”
  • 所以方法应该命名为test,而你要扩展的类型是SomeExtensionMethod的返回值是什么?它是什么类型的?
  • 我已经编辑了我的问题。我将通过方法名称说 test 或 test2 或 test3 并且以下行 users[username] 应该相应地调用该方法,如 users[username].test() 或 users[username] .test2

标签: c# c#-4.0 dynamic extension-methods


【解决方案1】:

不知道为什么需要这样做...

public class 1 {
    public void method(){
        //do stuff
    }
}

public class 2 {
    public void method2(){
        dynamic users = BLClass.MYBLMethod();
        List<string> usernames = BLClass.MYBLSecondMethod();
        foreach (string username in usernames)
        {
             1.method(users[username]);
         }
    }
 }

这会更简单吗?

【讨论】:

    【解决方案2】:

    我不确切知道您的类型是什么样的,但您可以使用 GetMethod() 按名称调用方法。

    public static class Extensions
    {
        public static void SomeExtensionMethod(this BLClass blclass, string methodname)
        {
            dynamic users = blclass.MYBLMethod();
            List<string> usernames = blclass.MYBLSecondMethod();
            foreach (string username in usernames)
            {
                var user = users[username];
                user.GetType().GetMethod(methodname).Invoke(user, null);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      相关资源
      最近更新 更多