Вход на сайт
C# не работает контравариация в параметрах делегатов
612 просмотров
Перейти к просмотру всей ветки
в ответ alex445 3 дня назад, 15:09, Последний раз изменено 3 дня назад, 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
}
}
Назад