【问题标题】:Attempting to set multiple values of a private field of int array through a public property outside of its class试图通过其类之外的公共属性设置 int 数组的私有字段的多个值
【发布时间】:2013-01-06 05:42:53
【问题描述】:

我正在尝试通过公共属性访问器从类外部设置整数数组的私有字段。我几乎可以肯定问题是我缺乏完成这项工作的语法知识。如果我在通过对象访问属性时指定数组的索引,我已经想出了如何设置单个值。这是我目前所拥有的。

下面是我的班级。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace paramRefVal
{
    class ParamaterTest
    {
        private int[] _ints = new int[5];
        private int _i;

        public int[] Ints
        {
            get { return _ints; }
            set { _ints = value; }
        }

        public int I
        {
            get { return _i; }
            set { _i = value; }
        }

        public void SomeFunction(int[] Ints, int I)
        {
            Ints[0] = 100;
            I = 100;
        }
    }
}

这是我的主要方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace paramRefVal
{
    class Program
    {
        static void Main(string[] args)
        {
            ParamaterTest paramTest = new ParamaterTest();
            paramTest.I = 0;
            paramTest.Ints[0] = 99;
            Console.WriteLine("Ints[0] = {0}", paramTest.Ints[0]);
            Console.WriteLine("I = {0}", paramTest.I);
            Console.WriteLine("Calling SomeFunction...");
            paramTest.SomeFunction(paramTest.Ints, paramTest.I);
            Console.WriteLine("Ints[0] = {0}", paramTest.Ints[0]);
            Console.WriteLine("I = {0}", paramTest.I);
            Console.ReadLine();
        }
    }
}

我感兴趣的行是

paramTest.Ints[0] = 99;

我尝试设置多个值,但无济于事。

paramTest.Ints[] = { 0, 1, 2, 3, 4 };

我收到两个编译错误。 “找不到类型或命名空间名称'paramTest'(您是否缺少 using 指令或程序集引用?)”没有引号。

其次。不带引号的“预期标识符”。

感谢您的帮助!

【问题讨论】:

  • 您的代码在我的 VS2012 中运行,没有关于 paramTest 的编译器错误。
  • 制作“class ParamaterTest”->“public class ParamaterTest”来解决第一个错误。
  • C.朗。请注意,我说我绕过了这个问题,并且问题在一行代码中说明了。

标签: c# arrays properties field


【解决方案1】:

你可以使用:

paramTest.Ints = new int[] { 0, 1, 2, 3, 4 };

可以简化为:

paramTest.Ints = new[] { 0, 1, 2, 3, 4 };

如果你想使用数组初始化器,你可以这样做:

int[] ints = {0, 1, 2, 3, 4};
paramTest.Ints = ints;

不过,我没有收到关于该类型的任何编译错误。你能说得更具体一点吗?

【讨论】:

  • 谢谢。一旦我包含了新的关键字,一切都是 honkey dorey。非常感谢夏娃!关于类型,也许我们使用的是不同版本的 IDE?我在 Windows 8 中使用 VS 2012。无论哪种方式,新关键字都修复了它。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2012-10-29
  • 2019-04-19
  • 2015-06-09
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-18
相关资源
最近更新 更多