将项添加到列表中

时间:2014-01-10 10:39:35

标签: c# list token

在Visual Studio中,如何设置用户创建对象的属性?

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Gms.Maps.Model;

namespace SimpleMapDemo
{
    class MapLocation
    {
        public MapLocation()
        {
        }

        public LatLng Location;
        public BitmapDescriptor icon;
        public String Snippet;
        public String Title;
    }
}

我想添加这些项目的列表,我已经完成了以下代码:

private List<MapLocation> MapLocationList = new List<MapLocation>();
MapLocation MapLocationItem = new MapLocation();
MapLocationItem.Title = "Title";

以下是我收到的错误:

Invalid token '=' in class, struct, or interface member declaration

我可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

您可以使用构造函数或collection/object initializer syntax,这两种方式都可以:

class MapLocation
{
    // constructor
    public MapLocation()
    {
        MapLocationList = new List<MapLocation>();
        MapLocation MapLocationItem = new MapLocation();
        MapLocationItem.Title = "Title";
        MapLocationList.Add(MapLocationItem);
    }

    // collection initializer
    private List<MapLocation> MapLocationList = new List<MapLocation>()
    {
          // object initializer
          new MapLocation
          {
            Title = "Title"
          }
    };

    public string Title{get;set;}
}

答案 1 :(得分:0)

您无法在类主体中访问(从而分配或检索)您的实例(称为MapLocationItem)。这只有在你在构造函数,函数,getter或setter中时才有可能(可能我会忘记一两个)。

class MainClass
{
    // Define the list of map locations in the body of the class
    // It is private thus only available from within the class itself
    // Added underscore '_' to it that is quite common for private mmebers
    private List<MapLocation> _mapLocationList = new List<MapLocation>();

    public MainClass()
    {
        // Create an instance of the MapLocation, only valid within the constructor scope
        MapLocation item = new MapLocation();
        // Set the property of the instance
        item.Title = "Title";

        // Adds the MapLocation instance 'item' to the list of MapLocations
        _mapLocationList.Add(item);
    }
}

答案 2 :(得分:0)

您需要设置属性。做类似下面的事情:

class MapLocation
    {
        public MapLocation()
        {
        }

        public LatLng Location {get; set;}
        public BitmapDescriptor icon {get; set;}
        public String Snippet {get; set;}
        public String Title {get; set;}
    }
}