c# - 如何在函数中将对象列表作为参数传递,然后使用对象的属性C#
问题描述
这就是我的功能:
public bool CheckUniqueName<T>(string newName, List<T> list)
{
for (int i = 0; i < list.Count(); i++)
{
if (list[i].name == newName)
{
return false;
}
}
return true;
}
我有这个行星列表:private List<Planet> planetsList = new List<Planet>();
但是:我将使用其他列表,public List<Colony> ColonyList = new List<Colony>();
这就是我需要的原因List<T>
和类Planet
:
class Planet
{
...
public string name { get; }
...
}
我试试这个:(some stuff) CheckUniqueName(name, planetsList)
在其他班级
据我了解,List<T>
不知道该.name
属性。
我尝试创建另一个列表并执行以下操作:
public bool CheckUniqueName<T>(string newName, List<T> list)
{
if (list is List<Planet>)
{
var newList = planetsList;
}
for (int i = 0; i < list.Count(); i++)
{
if (list[i].name == newName)
{
return false;
}
}
return true;
}
它不起作用,创建新列表的同样事情也不起作用。
解决方案
您可以在此处使用通用约束:
public bool CheckUniqueName<T>(string newName, IEnumerable<T> items)
where T : INamed
=> !items.Any(i => (i.Name == newName));
public interface INamed
{
public Name { get; }
}
public class Planet : INamed
{
public Name { get; }
public Plant(string name)
{
Name = name;
}
}
public class Colony : INamed
{
public Name { get; }
public Colony(string name)
{
Name = name;
}
}
推荐阅读
- python - 如何在 Windows 上安装 Morfeusz2 for Python?
- sql-server - 我需要设置 SSMS 以在不同的域上运行 (runas.exe) 如何帮助我的用户识别 ssms.exe 文件的路径?
- maven - Maven:摆脱旧的依赖
- symfony - Symfony Twig - 如何将参数放入替换 - 错误
- html - ul type="circle" 的圆圈周围的红色椭圆
- java - 我关于通过 css 选择器查找元素的 Selenium 的问题
- arrays - Creating an Dynamic Tables in MS-SQL (feasibility)
- windows - Record region of screen using FFMPEG?
- ember.js - How to use route's params in adapter in Ember.js?
- php - Symfony : make:crud 与 ManyToOne 关系