繁体   English   中英

如何在 function 中将对象列表作为参数传递,然后使用对象的属性 C#

[英]How to pass list of objects as parameter in function and then use object's attributes C#

这就是我的 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;
    }

我有这个行星列表: private List<Planet> planetsList = new List<Planet>();

但是:我将使用其他列表,例如public List<Colony> ColonyList = new List<Colony>(); 这就是为什么我需要List<T>

和 class Planet

class Planet
{
    ...
    public string name { get; }
    ... 
}

我试试这个:( (some stuff) CheckUniqueName(name, planetsList)在其他class

据我所知, 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;
    }
}

另一种方法是传递一个委托,该委托知道如何从您传入的任何类型中获取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;
}

像这样称呼它:

CheckUniqueName(planetsList, "name", planet => planet.name);

那么你的name属性不必被称为name - 它可以被称为任何你想要的。


为了清楚起见,我编写了CheckUniqueName方法的长版本,但您可以使用 linq 缩短它:

public bool CheckUniqueName<T>(IEnumerable<T> items, string newName, Func<T, string> nameSelector)
{
    return !items.Any(item => newName == nameSelector(item));
}

但是,一旦您到此为止 go ,您不妨完全放弃CheckUniqueName方法,而只需编写:

!plantsList.Any(x => x.name == "name");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM