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

它不起作用,创建新列表的同样事情也不起作用。

标签: c#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;
    }
}

推荐阅读