这就是我的功能:
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;
}
它不起作用,创建新List的相同操作也不起作用。
最佳答案
您可以在此处使用一般约束:
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;
}
}
关于c# - 如何将对象列表作为函数中的参数传递,然后使用对象的属性C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58397141/