相关疑难解决方法(0)

通用扩展方法:无法从用法推断出类型参数

我正在尝试创建一个适用于类型化数据表的通用扩展方法:

public static class Extensions
{
    public static TableType DoSomething<TableType, RowType>(this TableType table, param Expression<Func<RowType, bool>>[] predicates)
        where TableType : TypedTableBase<RowType>
        where RowType : DataRow
    {
        // do something to each row of the table where the row matches the predicates
        return table;
    }

    [STAThread]
    public static void main()
    {
        MyTypedDataSet.MyTypedDataTable table = getDefaultTable();
    }

    public static MyTypedDataSet.MyTypedDataTable getDefaultTable()
    {
        // this line compiles fine and does what I want:
        return new MyTypedDataSet.MyTypedDataTable().DoSomething<MyTypedDataSet.MyTypedDataTable, MyTypedDataSet.MyTypedRow>(row => row.Field1 == "foo");

        // this …
Run Code Online (Sandbox Code Playgroud)

c# database generics lambda

15
推荐指数
1
解决办法
8476
查看次数

C#Json反序列化为通用对象

我有一个具有自己的对象类型的函数:

public RaceJson GetLatestRace()
{
     string filter = "example";
     List<RaceJson> currentRace = await gsaClient.SendCustomRequest<List<RaceJson>>("races?$filter=" + filter);
     return currentRace.FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)

我想使用它们都将使用的通用函数。我希望它是通用的,并将对象反序列化为我要发送的类型。我目前有:

    public async Task<T> SendCustomRequest<T>(string odataFilter)
    {
        string response = await SendRequestAsync(odataFilter, true);

        if( !string.IsNullOrEmpty(response))
        {
            T converted = JsonConvert.DeserializeObject<T>(response);
            return converted;
        }

        return default;
    }
Run Code Online (Sandbox Code Playgroud)

尝试反序列化列表时出现错误:

JsonSerializationException:无法将当前JSON对象(例如{“ name”:“ value”})反序列化为类型'System.Collections.Generic.List`1 [tf_gsa_client.Models.HorseRacing.RaceJson]',因为该类型需要JSON数组(例如[1,2,3])以正确反序列化。要解决此错误,可以将JSON更改为JSON数组(例如[1,2,3]),也可以更改反序列化类型,使其成为普通的.NET类型(例如,不像整数这样的原始类型,也不像这样的集合类型。数组或列表),可以从JSON对象反序列化。还可以将JsonObjectAttribute添加到类型中,以强制其从JSON对象反序列化。

谢谢。

c# serialization json types object

0
推荐指数
1
解决办法
74
查看次数

标签 统计

c# ×2

database ×1

generics ×1

json ×1

lambda ×1

object ×1

serialization ×1

types ×1