如何将对象列表作为函数中的参数传递,然后使用对象的属性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;
    }

它不起作用,创建新List的相同操作也不起作用。

你74

您可以在此处使用一般约束:

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;
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章