[英]How to pass list of objects as parameter in function and then use object's attributes C#
So that's my function:这就是我的 function:
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;
}
I have this List of Planets: private List<Planet> planetsList = new List<Planet>();
我有这个行星列表:
private List<Planet> planetsList = new List<Planet>();
BUT: I'm gonna use other Lists like public List<Colony> ColonyList = new List<Colony>();
但是:我将使用其他列表,例如
public List<Colony> ColonyList = new List<Colony>();
That's why I need List<T>
这就是为什么我需要
List<T>
And class Planet
:和 class
Planet
:
class Planet
{
...
public string name { get; }
...
}
And I try this: (some stuff) CheckUniqueName(name, planetsList)
in other class我试试这个:(
(some stuff) CheckUniqueName(name, planetsList)
在其他class
As I get it, List<T>
doesn't know about the .name
attribute.据我所知,
List<T>
不知道.name
属性。
I tried to create another List and do something like this:我尝试创建另一个列表并执行以下操作:
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;
}
It didn't work and same things with creating new List didn't work as well.它不起作用,创建新列表的同样事情也不起作用。
You can using generic constraints here:您可以在此处使用通用约束:
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;
}
}
Another way to do this is to pass a delegate which knows how to fetch the name
property off any type you pass in:另一种方法是传递一个委托,该委托知道如何从您传入的任何类型中获取
name
属性:
public bool CheckUniqueName<T>(IEnumerable<T> items, string newName, Func<T, string> nameSelector)
{
foreach (var item in items)
{
string name = nameSelector(item);
if (name == newName)
{
return false;
}
}
return true;
}
Call it like this:像这样称呼它:
CheckUniqueName(planetsList, "name", planet => planet.name);
Then your name
property doesn't have to be called name
-- it can be called whatever you want.那么你的
name
属性不必被称为name
- 它可以被称为任何你想要的。
I wrote a long version of the CheckUniqueName
method for clarity, but you could shorten it using linq:为了清楚起见,我编写了
CheckUniqueName
方法的长版本,但您可以使用 linq 缩短它:
public bool CheckUniqueName<T>(IEnumerable<T> items, string newName, Func<T, string> nameSelector)
{
return !items.Any(item => newName == nameSelector(item));
}
However once you go this far, you might as well discard the CheckUniqueName
method entirely, and instead just write:但是,一旦您到此为止 go ,您不妨完全放弃
CheckUniqueName
方法,而只需编写:
!plantsList.Any(x => x.name == "name");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.