【问题标题】:Getting errors Working with HashSet使用 HashSet 时遇到错误
【发布时间】:2013-02-14 20:51:58
【问题描述】:

我创建了一个包含HashSet 的类来跟踪1-10 的整数。我使用Contain 方法检查是否在HashSet 中插入了一个值,并带有一个布尔值。这是我的代码:

class BasicIntSet
{
    HashSet<int> intTest = new HashSet<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    bool has4 = intTest.Contains(4);    // Returns true
    bool has11 = intTest.Contains(11);  // Returns false
    bool result = intTest.IsSupersetOf(new[] { 4, 6, 7 });
}

我现在的问题是,我收到一条错误消息,上面写着"Error 1 A field initializer cannot reference the non-static field, method, or property"

有人知道我做错了什么吗?

【问题讨论】:

  • 你知道你可以评论on an answer,例如如果它不适合你?

标签: c# hashset


【解决方案1】:

您的所有代码都在类声明中...您正在声明实例字段。您不能让一个实例字段初始化器引用另一个(或以任何其他方式引用 this),因此会出现错误。

修复它很简单 - 将代码放入方法中:

using System;
using System.Collections.Generic;

class BasicIntSet
{
    static void Main()
    {
        HashSet<int> intTest = new HashSet<int> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

        Console.WriteLine(intTest.Contains(4)); // True
        Console.WriteLine(intTest.Contains(11)); // False
        Console.WriteLine(intTest.IsSupersetOf(new[] { 4, 6, 7 })); // True
    }
}

请注意,您的原始错误与HashSet&lt;T&gt; 完全无关。这是我能想到的最简单的例子:

class BadFieldInitializers
{
    int x = 10;
    int y = x;
}

这给出了同样的错误 - 因为同样,一个字段初始化器(y)隐式引用了this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多