如何使这个IEnumerable循环通用?

问题描述 投票:1回答:1

我认为这种方法可以转换成通用的。然后我可以将它用于任何可枚举的类型。我该怎么做这个通用的?

private bool AreAnyInteractablesInThisList(
    IEnumerable<Interactable> Interactables, 
    Interactable InteractableToCheck)
{
    foreach (var Interactable in Interactables)
    {
        if (Interactable.GetInstanceID() == InteractableToCheck.GetInstanceID()) 
            return true;
    }
    return false;
}
c# generics
1个回答
3
投票

您需要创建一个声明GetInstanceID()方法的接口:

public interface IInteractable
{
    int GetInstanceID(); // I guess it's an int, but you can change that accordingly
}

然后使用泛型参数必须实现该接口的约束使方法通用:

private bool AreAnyInteractablesInThisList<T>(IEnumerable<T> Interactables, T InteractableToCheck) where T : IInteractable
{
    foreach (var Interactable in Interactables)
    {
        if (Interactable.GetInstanceID() == InteractableToCheck.GetInstanceID()) return true;
    }
    return false;
}

请注意,您可以将方法缩短为:

private bool AreAnyInteractablesInThisList<T>(IEnumerable<T> Interactables, T InteractableToCheck) where T : IInteractable
{
    // I cache this ID (assuming it was not changing with each call)
    int idToCheck = InteractableToCheck.GetInstanceID();
    return Interactables.Any(interactable => interactable.GetInstanceID() == idToCheck);
}
© www.soinside.com 2019 - 2024. All rights reserved.