Menu
CoddyTech

Métodos genéricos

Lição 24 de 48 do curso C# para desenvolvedores Python da Coddy.

TypeVar do Python expressa uma relação semelhante entre entrada e saída para verificadores externos. Métodos genéricos em C# impõem essa relação durante a compilação. A verificação de veracidade de listas em Python pode testar se estão vazias, mas C# exige Length == 0 em vez de tratar um array como bool.

Um parâmetro de tipo genérico conecta os tipos de argumento e resultado sem usar conversões para object. A inferência de tipos geralmente escolhe T com base nos argumentos. Um valor alternativo padrão é explícito aqui, em vez de default(T), porque quem chama controla a política para valores ausentes. A sintaxe de método genérico é compatível com este compilador.

Referência em Python

from typing import TypeVar
T = TypeVar("T")
def first_or(values: list[T], fallback: T) -> T:
    return values[0] if values else fallback
print(first_or(["A", "B"], "none"))

Declarações de suporte em C#

static T Echo<T>(T value) { return value; }

Instruções em C# dentro de Main

Console.WriteLine(Echo("A"));

Estes são trechos didáticos focados. Os arquivos do desafio incluem estruturas executáveis completas; os trechos acima mostram as declarações e instruções relevantes.

Saída de referência:

A

Saída em C#:

A
challenge icon

Desafio

Fácil

Implemente FirstOr<T> para vetores. Retorne o primeiro elemento ou o valor alternativo se o vetor estiver vazio. Solve usa números inteiros; o programa de teste bloqueado também usa strings para testar a API genérica.

Edite os arquivos C# desbloqueados. O arquivo bloqueado visível Main.cs lê as linhas descritas, chama Exercise.Solve, verifica se a entrada não foi modificada e imprime o resultado com uma quebra de linha final. Mantenha as APIs declaradas. Não adicione um segundo Main nem imprima mensagens de diagnóstico.

O iniciador bloqueado também testa a API da função auxiliar ou da classe exportada de forma independente, não apenas o wrapper Solve.

Experimente você mesmo

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Ints(input[0]); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);
if (Exercise.FirstOr(new string[0], "none") != "none" || Exercise.FirstOr(new[]{""}, "fallback") != "") throw new Exception("Generic API");
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de C# para desenvolvedores Python

Pratique por conta própria: Compilador de C# online