因此,我想从我的枚举值列表中知道有多少个特定的枚举值。
所以我写得像
public int GetNumFromList(List<Elements> list, Elements eType)
{
IEnumerable<Elements> query = //list.Where(p => p.GetType() == eType);
from listchild in list
where listchild == eType
select listchild;
/*
Debug.Log("Cur check type is " + eType + " and now selected number is " + query.Count());
if(query.Count() > 0)
Debug.Log(" and query 0 value is "+ query.ToArray().GetValue(0) + " type is "+ query.ToArray().GetValue(0).GetType());
*/
return query.Count();
}
public enum Elements{Fire, Water, Wood, Metal, Earth, None}
所以这很好用,但是我可以使其更短更整洁吗?
//list.Where(p => p.GetType() == eType); This part doesn't worked.
以及如何使它成为泛型T?
最佳答案
我该如何针对T普通型?不仅适用于[Elements]枚举。
public int GetNumFromList<T>(IEnumerable<T> list, T eType)
where T : struct, IComparable, IFormattable, IConvertible
{
return list.Count(x => x.Equals(eType));
}
问题在于,没有明确的说法“ T必须是一个枚举”。要求T为值类型,并实现IComparable,IFormattable和IConvertible,可以消除许多(但不是全部)非枚举类型。