有没有更好的方法可以声明一个匿名类型,而不需要创建它的实例?
var hashSet = new [] { new { Name = (string)null } }.Take(0).ToHashSet(); // HashSet<T>
using (new Scope())
{
hashSet.Add(new { Name = "Boaty" });
hashSet.Add(new { Name = "McBoatface" });
}
using (new AnotherScope())
{
return names.Where(x => hashSet.Contains(new { x.Name }));
}
我不喜欢上面第一行采用的笨拙方法,但它确实使我可以在后来的不同作用域中使用HashSet。
编辑: 第二个例子稍微更全面:
private IEnumerable<Person> _people;
public IEnumerable<Person> People()
{
HashSet<T> hashSet;
using (var new Scope())
{
// load a filter from somewhere else (oversimplified here to a single literal objects of an anonymous type)
hashSet = new []
{
new { FirstName = "Boaty", LastName = "McBoatface" },
}.ToHashSet();
}
using (var new AnotherScope())
{
return _people.Where(x => hashSet.Contains(new { FirstName = x.Nombre, LastName = x.Apellido }));
}
}
variable.ToHashSet()
方法。或者您可以编写一个函数来实现。但是,创建匿名类型的唯一方法是创建其实例。 - Dennis_Eusing (var new Scope())
就不是有效的。现在你写的是new [] { hashSet.Add(new {...etc
,你的意思应该是new [] { new { ...etc
。 - Dennis_E