调用不同变量类型的两个参数?

时间:2010-07-27 16:12:04

标签: c# variables invoke

如何使用两个不同变量类型的参数编写一个invoke方法?

    public void InsertStockPrice(double Value, string Company)
    {
        if (InvokeRequired)
        {
            Invoke(new Action<double>(InsertStockPrice), Value); // <- Not sure what to do here
        }
        else
        {
            //Do stuff
        }
    }

3 个答案:

答案 0 :(得分:4)

怀疑这就是吉米的意思(因为Control.Invoke真的不知道如何处理Action<double, string>

public void InsertStockPrice(double value, string company)
{
    if (InvokeRequired)
    {
        MethodInvoker invoker = () => InsertStockPrice(value, company);
        Invoke(invoker);
    }
    else
    {
        // Do stuff
    }
}

如果你正在使用C#2:

public void InsertStockPrice(double value, string company)
{
    if (InvokeRequired)
    {
        MethodInvoker invoker = delegate { InsertStockPrice(value, company); }
        Invoke(invoker);
    }
    else
    {
        // Do stuff
    }
}

请注意,我已经更改了参数的大小写,以适应正常的.NET约定。

答案 1 :(得分:0)

我认为您的意思是:

Action<Type1,Type2> yourAction = (type1Var, type2Var) => 
    {
       do stuff with type1Var and type2Var;
    }

yourAction(var1, var2);

答案 2 :(得分:0)

如果在代码中经常重复这种模式,你可以像这样做一个小辅助方法

static class UiExtensions
{
    public static void SafeInvoke(this Control control, MethodInvoker method)
    {
        if (control.InvokeRequired)
            control.Invoke(method);
        else
            method();
    }
}

this.SafeInvoke(() => { InsertStockPrices(value, company); });