0

我不确定如何创建对象列表。我得到“不可调用的成员 ListObjects.TestObject.UniqueID' 不能像方法一样使用。”

任何见解都会有所帮助。

我正在尝试创建以下对象的代码:

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

namespace ListObjects
{
    class TestObject
    {
        public int UniqueID { get; set; }


    }
}

主要代码:

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

namespace ListObjects
{
    class Program
    {
        static void Main(string[] args)
        {
            TestObject TestObject = new TestObject();
            List<TestObject> ObjectList = new List<TestObject>();

            ObjectList.Add(new TestObject().UniqueID(1));
            ObjectList.Add(new TestObject().UniqueID(10));
            ObjectList.Add(new TestObject().UniqueID(39));

        }
    }
}
4

5 回答 5

2

公共 int UniqueID { 获取;放; } 不是一个方法,它是一个 setter,你像方法一样使用它

做这个

ObjectList.Add(new TestObject()
{
    UniqueID = 1
});
于 2013-09-19T01:55:13.397 回答
2

您正在使用 UniqueId 之类的方法。它是一个属性,必须分配。如果您知道在创建 TestObject 时将分配一个 ID,您应该让构造函数支持它,并相应地使用它。如果没有,请使用ObjectList.Add(new TestObject { UniqueID = 1 });在没有构造函数的情况下分配值。

这就是我处理这种情况的方式:

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

namespace ListObjects
{
    class TestObject
    {
        public int UniqueID { get; set; }

        public TestObject(int uniqueId)
        {
            UniqueID = uniqueId;    
        }
    }
}

主要代码:

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

namespace ListObjects
{
    class Program
    {
        static void Main(string[] args)
        {
            List<TestObject> ObjectList = new List<TestObject>();

            ObjectList.Add(new TestObject(1));
            ObjectList.Add(new TestObject(10));
            ObjectList.Add(new TestObject(39));

        }
    }
}
于 2013-09-19T02:05:01.367 回答
2

我无法记住语法,但它来自记忆:

替换这一行:

ObjectList.Add(new TestObject().UniqueID(1));

用这条线:

ObjectList.Add(new TestObject(){UniqueID = 1});

并对所有 .Add 行执行相同操作。

于 2013-09-19T01:57:34.363 回答
1

这里发生了几件事。您不需要对象的实例来声明列表,只需要类型即可。

另外,UniqueID是属性,而不是方法。您为它们分配值(或从中读取值),您不会像方法的参数那样传递值。

您还可以在一次调用中初始化列表,如下所示:

List<TestObject> ObjectList = new List<TestObject>() 
                 { new TestObject() { UniqueID = 1}, 
                   new TestObject() { UniqueID = 10 },
                   new TestObject() { UniqueID = 39 } };

这将产生一个新的List<T>where Tis 类型TestObject,并且列表被初始化为 3 个实例TestObject,每个实例都用 的值初始化UniqueID

于 2013-09-19T01:59:14.720 回答
0
 TestObject TestObject = new TestObject();

删除此行。

并将以下行编辑为此语法

new TestObject { UniqueID = 39 }
于 2013-09-19T01:55:20.127 回答