[英]How to pass HashSet type into method
I have two different classes Student and Teacher in C#.我在 C# 中有两个不同的班级学生和教师。 Instances of these classes are stored in separated HashSets.这些类的实例存储在单独的 HashSet 中。 Both classes are interited from class Human.这两个类都是从类 Human 中继承而来的。
HashSet<Student> students
HashSet<Teacher> teachers
I would like to pass them into one method to sort them/print them, like我想将它们传递给一种方法来对它们进行排序/打印,比如
Sort(students);
Sort(teachers);
private void SortPeople<T>(HashSet<T> people)
{
// ... sorting function
}
But that does not work, the collection people in sorting function does not recognize it (cannot see atributes of Students/Teachers).但这不起作用,排序功能中的集合人员无法识别它(看不到学生/教师的属性)。 What would be the right solution?什么是正确的解决方案? Thank you.谢谢你。
My sugestion is for you to use an interface for the generic ...我的建议是让您使用通用接口...
void SortPeople<T>(HashSet<T> people)
where T : IPeople
{
}
public class Student : IPeople
{
public string Name { get; set; }
public int Id { get; set; }
}
public class Teacher : IPeople
{
public string Name { get; set; }
public int Id { get; set; }
}
public interface IPeople
{
string Name { get; set; }
int Id { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.