我有一个用于静态引用的响应类,在该类中包含许多集合-我的问题是我只想返回count> 0但我遇到GetEnumerator
问题的集合。我研究了实现IEnumberable
的不同方法,但仍然没有成功。
public class ReferencesResponse : BaseResponse, IEnumerable
{
public ReferencesResponse(bool success, string errorMessage)
{
Success = success;
ErrorMessage = errorMessage;
Init();
}
public ReferencesResponse()
{
Success = true;
Init();
}
internal void Init()
{
AuditTypes = new ObservableCollection<Reference>();
NoteTypes= new ObservableCollection<Reference>();
}
public ObservableCollection<Reference> AuditTypes { get; set; }
public ObservableCollection<Reference> NoteTypes{ get; set; }
这是参考响应类,用于返回所有集合。 一旦检查完数据库并将信息传递回去,我便得到了响应和所有内部集合,但是我无法访问“ Count”仅返回某些集合。
任何帮助或帮助者将不胜感激。
foreach (DataRow row in getReferences.Rows)
{
try
{
string col = row.Table.Columns[0].ColumnName;
ObservableCollection<Reference> values =
response.GetType().GetProperty(string.Concat(col, "s")).GetValue(response) as ObservableCollection<Reference>;
values.Add(ModelHelper.Reference(row, col));
}
catch
{
//Silent catch if reference type property has not been found
}
}
}
}
catch (Exception ex)
{
return null;
}
return response.Where(r => r.Count > 0);
}
答案 0 :(得分:0)
听起来您想枚举集合(而不是这些集合的内容),在这种情况下,您可以执行类似的操作
public IEnumerator GetEnumerator() {
IList tmp = AuditTypes;
if (tmp != null && tmp.Count != 0) yield return tmp;
tmp = NoteTypes;
if (tmp != null && tmp.Count != 0) yield return tmp;
// ...
}
如果您打算将列表的内容枚举为串联的块,那么我猜:
public IEnumerator GetEnumerator() {
IList tmp = AuditTypes;
if (tmp != null && tmp.Count != 0) foreach(var item in tmp) yield return item;
tmp = NoteTypes;
if (tmp != null && tmp.Count != 0) foreach(var item in tmp) yield return item;
// ...
}
但是请注意,仅实现IEnumerable
是非常不寻常的。通常,您需要为一些有意义的IEnumerable<T>
实现T
,因此消费者知道会发生什么。