我认为这种方法可以转换成通用的。然后我可以将它用于任何可枚举的类型。我该怎么做这个通用的?
private bool AreAnyInteractablesInThisList(
IEnumerable<Interactable> Interactables,
Interactable InteractableToCheck)
{
foreach (var Interactable in Interactables)
{
if (Interactable.GetInstanceID() == InteractableToCheck.GetInstanceID())
return true;
}
return false;
}
您需要创建一个声明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);
}