【问题标题】:Cannot apply indexing with [] to an expression of type 'method group' encapsulating an array无法使用 [] 将索引应用于封装数组的“方法组”类型的表达式
【发布时间】:2012-09-09 07:25:25
【问题描述】:

我正在构建这个简单的程序,但我遇到了一些问题。我将一个数组封装到一个类中,并用随机数填充它。在 Main 中我想使用 Console.WriteLine() 对其进行评估时,它会给出一个错误:

无法将带有 [] 的索引应用于“方法组”类型的表达式。

我做错了什么?

class Program
{
    public static void Main(string[] args)
    {
        Arrays randomArray = new Arrays();

        Console.WriteLine("Please type in an integer!");

        int encryptionKey = Convert.ToInt32(Console.ReadLine());
        randomArray.MyArray.SetValue(encryptionKey, 0);

        int i = 0;
        while (i < 256)
        {
            Console.WriteLine(i + "  " + randomArray.MyArray[i]);
            i++;
        }
        Console.ReadLine();
    }

    public static int[] MakeArray()
    {
        Random rnd = new Random();
        var value = Enumerable.Range(0, 256)
                              .Select(x => new { val = x, order = rnd.Next() })
                              .OrderBy(i => i.order)
                              .Select(x => x.val)
                              .ToArray();
        return value;
    }
}

public class Arrays
{
    private int[] _myArray;

    public int[] MyArray
    {
        get
        {
            return _myArray;
        }
        set 
        {
            _myArray = Program.MakeArray();
        }
    }
}

【问题讨论】:

    标签: c# .net arrays compiler-errors


    【解决方案1】:

    首先,排队

    randomArray.MyArray.SetValue(encryptionKey, 0);
    

    program 给你一个异常(空引用),因为在这一行中 MyArray 的 get 部分将执行并将 null 返回给调用者。所以你必须在类 (Arrays) 的构造函数中设置你的数组 (MyArray) 值,我认为这部分的设计是错误的

    set 
            {
                _myArray = Program.MakeArray();
            } 
    

    试试这个

    public class Arrays
    {
        public int[] _myArray;
    
        public Arrays() {
               MyArray = Program.MakeArray();
        }
    
        public int[] MyArray
        {
            get; set;
        }
    }
    

    这将解决问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      • 2018-04-03
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多