我如何可以通过在行动参数? [英] How can I pass a parameter in Action?

查看:173
本文介绍了我如何可以通过在行动参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void Include(IList<string> includes, Action action)
        {
            if (includes != null)
            {
                foreach (var include in includes)
                    action(<add include here>);
            }
        }

我想将它像

this.Include(includes, _context.Cars.Include(<NEED TO PASS each include to here>));

我们的想法是通过每个包含的方法。

The idea is pass each include to the method.

推荐答案

如果你知道你想传递什么样的参数,采取动作&LT; T&GT; 的类型。例如:

If you know what parameter you want to pass, take a Action<T> for the type. Example:

void LoopMethod (Action<int> code, int count) {
     for (int i = 0; i < count; i++) {
         code(i);
     }
}

如果你想参数传递给你的方法,使该方法一般:

If you want the parameter to be passed to your method, make the method generic:

void LoopMethod<T> (Action<T> code, int count, T paramater) {
     for (int i = 0; i < count; i++) {
         code(paramater);
     }
}

和主叫code:

Action<string> s = Console.WriteLine;
LoopMethod(s, 10, "Hello World");


更新。您的code应该是这样的:


Update. Your code should look like:

private void Include(IList<string> includes, Action<string> action)
{
    if (includes != null)
    {
         foreach (var include in includes)
             action(include);
    }
}

public void test()
{
    Action<string> dg = (s) => {
        _context.Cars.Include(s);
    };
    this.Include(includes, dg);
}

这篇关于我如何可以通过在行动参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆