有没有更好的方法可以声明匿名类型,而不必创建它的实例?

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 }));
}

我不喜欢上面第一行中使用的看起来很粗糙的方法,但是它允许我以后在不同的范围内使用散列集。
编辑:
第二,稍微全面一点,例如:
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 }));
    }
}

最佳答案

事实上没有办法做到这一点,匿名对象总是有一些对象初始化(这是通过使用new)。
匿名类型是一种设置和忘记,这意味着使用它们一次-通常在短代码中,例如LINQ表达式-然后忘记它们曾经存在。
但是你应该问问自己为什么你需要这个。当你需要你的类中的列表时,给它的实体一个名字。在不同的作用域中使用相同的匿名类型有什么好处?要清楚准确。因此,每个开发人员都知道您的列表包含什么,以及他/她可以从中接受什么。
所以你最好使用一个(私有的)struct来实现这一点,它也可以在你的方法中使用。

class CyClass
{
    private struct Person { public string Name; }

    HashSet<Person> hashSet = new HashSet<Person>();

    ...

        using (var firstScope = new Scope())
        {
            hashSet.Add(new Person { Name = "Boaty" });
            hashSet.Add(new Person { Name = "McBoatface" });
        }

        using (var secondScope = new AnotherScope())
        {
            return names.Where(x => hashSet.Contains(new Person{ x.Name }));
        }
}

MSDN clearily states this:
如果必须存储查询结果或将其传递到方法边界之外,请考虑使用普通的命名结构或类,而不是匿名类型
不过,我不会将此限制为第二段中描述的方法边界。
编辑:如果可以在不实例化匿名类型的情况下创建匿名类型,请参见msdn中的以下句子:
通过将新运算符与
对象初始化器
编辑2:从C 7开始,您可以在列表中使用元组。然而,元组至少有twp属性,因此第一个示例在这里不起作用:
var myList = new List<string FirstName, string LastName>();
myList.Add(("Boaty", "McBoatface"));

现在您可以检查其他列表是否包含这样的元组:
var contained = anotherList.Contains(("Boaty", "McBoatface"));

关于c# - 如何在不创建C#匿名类型的情况下声明它的实例?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40651423/

10-11 22:05
查看更多