添加并填充 IEnumerable 属性 到 API 调用

Add and populate an IEnumerable property to an API call

我正在使用较旧的第 3 方 API 连接到遗留系统。

代码如下:

    AutoMaximizer.AuthUser yourCredentials = new AutoMaximizer.AuthUser
    {
        UserKey = "x1213"
    };

    AutoMaximizer.Pagers availableCars = new AutoMaximizer.Pagers
    {
        TotalCalls = 65,
        Router = 91220
    };

    ISessionManagement s = new ManagementClient();

    FactoryResponse response;

    response = await s.GetAll(yourCredentials, new ListRequest
    {
        Pagers = availableCars,
        SortIncreasing = true
    });

它正在运行,但我想在提出请求时再添加一个 属性。

这个属性叫做Types,是一个IEnumerable<Type>。 API 文档状态:

Types   =  Gets or sets an enumeration of types to include in the response.

并且在 API 参考中,我找到了它:

public enum Type : int
{
    
    [System.Runtime.Serialization.EnumMemberAttribute()]
    Auto = 0,
    
    [System.Runtime.Serialization.EnumMemberAttribute()]
    Truck = 1,
    
    [System.Runtime.Serialization.EnumMemberAttribute()]
    Motorcycle = 2
    
}

但我不太确定如何将它添加到 GetAll 方法中。

我试着添加这个:

List<AutoMaximizer.Type> types = new List<AutoMaximizer.Type>();
types.Add(AutoMaximizer.Type.Auto);
types.Add(AutoMaximizer.Type.Truck);
types.Add(AutoMaximizer.Type.Motorcycle);

然后是这个:

response = await s.GetAll(yourCredentials, new ListRequest
{
    Pagers = availableCars,
    SortIncreasing = true,
    Types = types
});

但这给了我这个错误:

Cannot implicitly convert type Systems.Collections.Generic.List<AutoMaximizer.Type> to AutoMaximizer.Type[]

我不知道现在该怎么办...

有没有办法让它工作?

谢谢!

阅读你的错误,它需要一个数组,而不是一个列表:

response = await s.GetAll(yourCredentials, new ListRequest
{
    Pagers = availableCars,
    SortIncreasing = true,
    Types = new[] { Type.Auto, Type.Truck, Type.Motorcycle },
});

根据错误,ListRequest 专门寻找一个数组,而不是任何通用集合。您可以将列表转换为数组:

response = await s.GetAll(yourCredentials, new ListRequest
{
    Pagers = availableCars,
    SortIncreasing = true,
    Types = types.ToArray()
});

或者只使用数组开头:

AutoMaximizer.Type[] types = new [] { AutoMaximizer.Type.Auto, AutoMaximizer.Type.Truck, AutoMaximizer.Type.Motorcycle };