代表似乎没有注册'params'

时间:2017-07-11 10:39:22

标签: c# delegates

C#的params关键字允许Array和parameter-list之间的等价,不是吗?

可悲的是,在我的实施中,情况并非如此。

private Entities queryType(String entitiesType, params KeyValuePair<String, object>[] values)
{
    addStandardHeaders();
    String query = parsePredicate(values);
    Task<HttpResponseMessage> filterTask = client.GetAsync(client.BaseAddress + RESTapi.ALMentitiesQuery(domain, project, entitiesType, query));
    Task.WaitAny(filterTask);
    //Callback:
    HttpResponseMessage result = filterTask.Result;
    if (result.IsSuccessStatusCode)
    {
        updateCookies(client.BaseAddress+RESTapi.ALMentitiesQuery(domain, project, entitiesType, query));
        mainHeaders.Clear();
        Task<Stream> output = result.Content.ReadAsStreamAsync();
        Task.WaitAny(output);
        //Callback:
        return (Entities)fromJSON(output.Result, typeof(Entities)); 
    }
    else
    {
        util.Exception exception = getException(result);
        throw new HttpException(exception.Title);
    }
}

代表:

public delegate Entities SubTypeQuery(String subType, params KeyValuePair<String, object>[] values);

在申请中:

public List<Run> getRuns()
{
    List<Entity> selection = ((Entities)subTypeSelector.DynamicInvoke(
        ALMObject.Run.entitiesName(),
        (new KeyValuePair<String, object>("testcycle-id", id))
    )).entities.ToList<Entity>();

    List<Run> runSet = new List<Run>();
    foreach (Entity element in selection)
        runSet.Add(new Run(element, subTypeSelector));
    return runSet;
}

在运行时,我遇到类型异常:“无法将KeyValuePair<String, object>转换为KeyValuePair<String, object>[]”。这使得params完全没用。 建议?

3 个答案:

答案 0 :(得分:2)

  

C#的params关键字允许Array和parameter-list之间的等价,不是吗?

当涉及C#(或VB)编译器时,是的。不是在你使用反射时。

问题是你动态调用委托 - 基本上是用反射。反射代码 没有注意到params。您需要直接调用委托(不使用DynamicInvoke)或明确创建数组。

答案 1 :(得分:2)

为什么动态调用?您似乎知道所有参数的类型。

只是调用代表?

List<Entity> selection = ((Entities)subTypeSelector(
    ALMObject.Run.entitiesName(),
    (new KeyValuePair<String, object>("testcycle-id", id))
)).entities.ToList<Entity>();

答案 2 :(得分:0)

我建议改变:

new KeyValuePair<String, object>("testcycle-id", id)

为:

new [] { new KeyValuePair<String, object>("testcycle-id", id) }

另见one for Spark