русский

C# не работает контравариация в параметрах делегатов

3 Tage zurück, 15:24
Re: C# не работает контравариация в параметрах делегатов
 
alex445 патриот
in Antwort alex445 3 Tage zurück, 15:09, Zuletzt geändert 3 Tage zurück, 15:27 (alex445)

Что говорит ИИ - и даёт код, аналогичный моему.


C# create delegate through lambda with parameter of type inherited from the original delegate parameter type


using System;

// Base and derived classes
public class Animal
{
    public string Name { get; set; }
}

public class Dog : Animal
{
    public string Breed { get; set; }
}

// Delegate that takes a base type parameter
public delegate void AnimalHandler(Animal animal);

class Program
{
    static void Main()
    {
        // Create delegate instance using a lambda with a derived type parameter
        AnimalHandler handler = (Dog d) =>
        {
            Console.WriteLine($"Dog name: {d.Name}, Breed: {d.Breed}");
        };

        // Works with base type argument because delegate expects Animal
        handler(new Dog { Name = "Rex", Breed = "German Shepherd" });

        // This would cause a runtime cast error if you pass a non-Dog Animal
        // handler(new Animal { Name = "Generic Animal" }); // InvalidCastException
    }
}
 

Sprung zu