首页 > 解决方案 > 协方差泛型 c#

问题描述

这是一个取自 MSDN的示例,用于 C# 中泛型的协变。

我无法打印 FullName,我能知道为什么输出没有打印吗?

// Simple hierarchy of classes.  
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Employee : Person { }

public class Print
{
    // The method has a parameter of the IEnumerable<Person> type.  
    public static void PrintFullName(IEnumerable<Person> persons)
    {
        foreach (Person person in persons)
        {
            Console.WriteLine("Name: {0} {1}",
            person.FirstName, person.LastName);
        }
    }
}
class Program
{
    public static void Main()
    {
        IEnumerable<Person> employees = new List<Person>();
        Person person = new Person();
        person.FirstName = "nuli";
        person.LastName = "swathi";
        Print.PrintFullName(employees);
        Console.ReadKey();
    }
}

标签: c#c#-4.0

解决方案


因为你的employees清单是空的。

您应该将您的 Person 实例添加到employees列表中,然后您会看到它被打印出来。

IE

class Program
{
    public static void Main()
    {
        IList<Person> employees = new List<Person>(); //you need to declare this as a List/IList to get the `Add` method
        Person person = new Person();
        person.FirstName = "nuli";
        person.LastName = "swathi";

        //add this line
        employees.Add(person);

        Print.PrintFullName(employees);
        Console.ReadKey();
    }
}

推荐阅读