c# - 协方差泛型 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();
}
}
解决方案
因为你的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();
}
}
推荐阅读
- python - 创建相似度矩阵的有效方法(熊猫)
- vue.js - 使用 VueJS 将数据从子级发送到父级
- sql - 如何将字符串列分配给变量并在 Bash 脚本的输出中引用它
- javascript - 在单元测试期间我应该模拟哪些功能
- javascript - 使用 formData 提交表单后,php 中的 $_POST 数组为空
- amazon-cloudsearch - 或使用 CloudSearch 的结构化查询解析器搜索相同的字段
- laravel - DOMPDF - 下载选定日期的报告
- mongodb - MongoDB:如果元素不存在,则通过向其添加元素来更新文档中的列表
- lua - 为什么这个输出“nan”(lua)
- reactjs - 如何将函数设置为在另一个函数之后呈现?