AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79055044
Accepted
Mammt
Mammt
Asked: 2024-10-04 23:56:57 +0800 CST2024-10-04 23:56:57 +0800 CST 2024-10-04 23:56:57 +0800 CST

O objeto de retorno não é aquele declarado pela assinatura quando invocado por meio de reflexão

  • 772

Eu tenho uma PagedList<>classe que implementa uma interface chamadaIPagedList<>

A classe não tem um construtor público, mas pode ser criada por meio de um método estático chamadoCreate

    public static IPagedList<T> Create(IEnumerable<T> items, int pageNumber, int pageSize, int totalItems) {
        Ensure.That.IsNotNull(items);
        Ensure.That.IsNotZeroOrNegative(pageNumber);
        Ensure.That.IsNotZeroOrNegative(pageSize);

        var totalItemCount = totalItems;
        return new PagedList<T>(items, pageNumber, pageSize, totalItemCount);
    }

Este método simplesmente invoca o construtor que é declarado private protected.

Se o Createmétodo for invocado diretamente, o objeto retornado será umIPagedList<T>

Entretanto, quando o método é invocado por meio de reflexão, o tipo retornado é umPagedList<T>

Este é o código para reflexão

var typeToCall = typeof(PagedList<>).MakeGenericType(targetType);
MethodInfo createMethod = typeToCall.GetMethod("Create")!;
dynamic result = createMethod.Invoke(null, new object[] { value, pageNumber, pageSize, totalItems })!;
return (IPagedList)result!;

visualização de depuração

Esse comportamento é normal? Acontece porque estou usando dynamic?

Quando o objeto criado é retornado ao chamador, que espera um IPagedList<T>I obtém uma exceção que diz

System.InvalidCastException: Não é possível converter o objeto do tipo 'ApiResult 1[PagedList1[ProgramResponse]]' para o tipo 'ApiResult 1[IPagedList1[ProgramResponse]]'.

   at System.Text.Json.ThrowHelper.ThrowInvalidCastException_DeserializeUnableToAssignValue(Type typeOfValue, Type declaredType)
   at System.Text.Json.JsonSerializer.<UnboxOnRead>g__ThrowUnableToCastValue|50_0[T](Object value)
   at System.Text.Json.JsonSerializer.UnboxOnRead[T](Object value)
   at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value, Boolean& isPopulatedValue)
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 utf8Json, JsonTypeInfo`1 jsonTypeInfo, Nullable`1 actualByteCount)
   at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 json, JsonTypeInfo`1 jsonTypeInfo)

Estou incluindo o JsonConverter completo que desserializa o objeto IPagedList

internal class NativePagedListConverter : JsonConverter<IPagedList> {
    public override bool CanConvert(Type typeToConvert) {
        return typeToConvert.IsPagedList();
    }

    public override IPagedList? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
        if (reader.TokenType != JsonTokenType.StartObject) {
            throw new JsonException();
        }
        int pageNumber = 0;
        int pageSize = 0;
        int totalItems = 0;
        dynamic value = default!;
        var targetType = typeToConvert.GetGenericArguments()[0]!;
        while (reader.Read()) {
            if (reader.TokenType == JsonTokenType.EndObject) {
                break;
            }
            if (reader.TokenType != JsonTokenType.PropertyName) {
                throw new JsonException();
            }
            var propertyName = reader.GetString() ?? string.Empty;
            reader.Read();
            if (propertyName.Equals(nameof(pageNumber), StringComparison.OrdinalIgnoreCase)) {
                pageNumber = reader.GetInt32();
            }
            else if (propertyName.Equals(nameof(pageSize), StringComparison.OrdinalIgnoreCase)) {
                pageSize = reader.GetInt32();
            }
            else if (propertyName.Equals(nameof(totalItems), StringComparison.OrdinalIgnoreCase)) {
                totalItems = reader.GetInt32();
            }
            else if (propertyName.Equals("Items", StringComparison.OrdinalIgnoreCase)) {
                var itemsType = typeof(IEnumerable<>).MakeGenericType(targetType);
                value = JsonSerializer.Deserialize(ref reader, itemsType, options)!;
            }
        }
        var typeToCall = typeof(PagedList<>).MakeGenericType(targetType);
        MethodInfo createMethod = typeToCall.GetMethod("Create")!;
        dynamic result = createMethod.Invoke(null, new object[] { value, pageNumber, pageSize, totalItems })!;
        return (IPagedList)result!;
    }

    public override void Write(Utf8JsonWriter writer, IPagedList value, JsonSerializerOptions options) {
        [...omitted as not interesting for the question...]
    }

}
c#
  • 1 1 respostas
  • 63 Views

1 respostas

  • Voted
  1. Best Answer
    dbc
    2024-10-05T02:36:45+08:002024-10-05T02:36:45+08:00

    Embora você não tenha compartilhado suas implementações de ApiResult<T>or IPagedList<T>ou PagedList<T>, este parece ser um caso em que o padrão do conversor de fábrica seria necessário:

    O padrão de fábrica é necessário para genéricos abertos porque o código para converter um objeto de e para uma string não é o mesmo para todos os tipos. Um conversor para um tipo genérico aberto ( List<T>,por exemplo) tem que criar um conversor para um tipo genérico fechado ( List<DateTime>, por exemplo) nos bastidores. O código deve ser escrito para manipular cada tipo genérico fechado que o conversor pode manipular.

    Digamos que seus tipos sejam mais ou menos assim:

    public abstract record ApiResult
    {
        public static ApiResult<T> Create<T>(T result) => new ApiResult<T>(result);
    }
    
    public record ApiResult<T>(T Result) : ApiResult;
    
    public interface IPagedList
    {
        public IEnumerable Items { get; }
        public int PageNumber { get; }
        public int PageSize { get; }
        public int TotalItems { get; }
    }
    
    public interface IPagedList<out T> : IPagedList
    {
        public new IEnumerable<T> Items { get; }
    }
    
    public class PagedList<T> : IPagedList<T>
    {
        public IEnumerable<T> Items { get; }
        public int PageNumber { get; }
        public int PageSize { get; }
        public int TotalItems { get; }
        IEnumerable IPagedList.Items => Items;
    
        private protected PagedList(IEnumerable<T> items, int pageNumber, int pageSize, int totalItems) =>
            (this.Items, this.PageNumber, this.PageSize, this.TotalItems) = (items, pageNumber, pageSize, totalItems);
    
        public static IPagedList<T> Create(IEnumerable<T> items, int pageNumber, int pageSize, int totalItems) {
            //Ensure.That.IsNotNull(items);  // FIXED removed calls to undefined methods
            //Ensure.That.IsNotZeroOrNegative(pageNumber);
            //Ensure.That.IsNotZeroOrNegative(pageSize);
            return new PagedList<T>(items, pageNumber, pageSize, totalItems);
        }
    }
    

    Então você pode definir o seguinte conversor de fábrica e o conversor genérico interno da seguinte maneira:

    public class PagedListConverter : JsonConverterFactory
    {
        public override bool CanConvert(Type typeToConvert) => typeToConvert.IsPagedList();
        
        public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) =>
            (JsonConverter)Activator.CreateInstance(typeof(PagedListConverter<>).MakeGenericType(typeToConvert.GetPagedListItemType()!))!;
    }
    
    public class PagedListConverter<T> : JsonConverter<IPagedList<T>>
    {
        record DTO(IEnumerable<T> items, int pageNumber, int pageSize, int totalItems);
    
        public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(IPagedList<T>) || typeToConvert == typeof(PagedList<T>);
    
        public override IPagedList<T> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => 
            JsonSerializer.Deserialize<DTO>(ref reader, options) switch
            {
                var dto when dto is not null => PagedList<T>.Create(dto.items, dto.pageNumber, dto.pageSize, dto.totalItems),
                _ => PagedList<T>.Create(Enumerable.Empty<T>(), 0, 0, 0), // TODO: decide what to do in case a null value was encountered in the JSON
            };
            
        public override void Write(Utf8JsonWriter writer, IPagedList<T> value, JsonSerializerOptions options) =>
            JsonSerializer.Serialize(writer, new DTO(value.Items, value.PageNumber, value.PageSize, value.TotalItems), options);
    }
    
    public static class TypeExtensions
    {
        public static IEnumerable<Type> GetInterfacesAndSelf(this Type type)
            => (type ?? throw new ArgumentNullException()).IsInterface ? new[] { type }.Concat(type.GetInterfaces()) : type.GetInterfaces();
    
        public static bool IsPagedList(this Type type) => type.GetPagedListItemType() != null;
        
        public static Type? GetPagedListItemType(this Type type) => 
            type.GetInterfacesAndSelf()
                .Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IPagedList<>))
                .Select(t => t.GetGenericArguments()[0])
                .SingleOrDefault();
    }
    

    Agora digamos que você tem alguma classe de item, por exemplo, como segue:

    public class MyItem
    {
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
    

    Você poderá serializar e desserializar um PagedList<MyItem>ou IPagedList<MyItem>da seguinte maneira:

    var result = ApiResult.Create(
        PagedList<MyItem>.Create([new () { Name = "name 1", Price = 101.1M }], 3, 1, 20)
    );
    
    var options = new JsonSerializerOptions
    {
        Converters = { new PagedListConverter() },
        // Other options as required, e.g.
        WriteIndented = true,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    };
    
    var json = JsonSerializer.Serialize(result, options);
    
    var newResult = JsonSerializer.Deserialize<ApiResult<IPagedList<MyItem>>>(json, options);
    

    Notas:

    • No conversor interno, em vez de escrever e ler cada propriedade manualmente, pode ser mais fácil mapear o tipo a ser serializado para algum DTO interno e, em seguida, serializar e desserializar o DTO.

    • O padrão do conversor de fábrica pode não funcionar ao usar a geração de origem em um aplicativo AOT nativo . (Por exemplo Type.MakeGenericType(), e MethodInfo.MakeGenericMethod()não há garantia de que funcione em tal aplicativo.) Em vez disso, será necessário criar manualmente o conversor interno PagedListConverter<T>para todos os tipos T, por exemplo:

      var options = new JsonSerializerOptions
      {
          Converters = { 
              new PagedListConverter<MyItem>(),
              // Other PagedListConverter<T> converters as required
          },
          // Other options as required, e.g.
          WriteIndented = true,
          PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
      };
      

    Demonstração do violino aqui .

    • 1

relate perguntas

  • Polly DecorrelatedJitterBackoffV2 - como calcular o tempo máximo necessário para concluir todas as novas tentativas?

  • Wpf. Role o DataGrid dentro do ScrollViewer

  • A pontuação que ganhei na página do jogo com .NET MAUI MVVM não é visível em outras páginas. Como posso manter os dados de pontuação no dispositivo local

  • Use a hierarquia TreeView com HierarchicalDataTemplate de dentro de um DataTemplate

  • Como posso melhorar essa interface de validação no .NET?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve