当我在类中使用类时,我得到一个空引用异常

时间:2018-05-09 16:18:18

标签: c#

我正在使用一个具有另一个类成员的类(所有成员都是字符串),当我尝试设置一个值时,我得到一个空引用异常。谁能帮我?我还是班上的新手。

以下是我的两个课程:

 loadMap() {

      this.geolocation.getCurrentPosition().then((position) => {
      let latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      let mapOptions = {
        center: latLng,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);


      //Red pin shows users position on the map
      var myPositionMarker = new google.maps.Marker({
        map: this.map,
        position: latLng, 
        icon: 'assets/imgs/pins/redpin.png',
        enableHighAccuracy:true
      })


      //For position update(this is a code which is not working)
        let watch = this.geolocation.watchPosition();
        watch.subscribe((data) => {
       // data can be a set of coordinates, or an error (if an error occurred).
       // data.coords.latitude
       // data.coords.longitude
       });

这是我设置CITY值的地方:

    public class MergeFields
    {
        public string FNAME { get; set; }
        public string LNAME { get; set; }
        public string CITY { get; set; }
        public string STATE { get; set; }
    }


    public class Member
    {
        public string email_Address { get; set; }
        public string status { get; set; }
        public MergeFields merge_fields { get; set; }
    }

我错过了一些明显的愚蠢的东西吗?或者这是不可能的?

2 个答案:

答案 0 :(得分:2)

是的,你是。你有两个选择:

  1. 显式类初始化:

    person.merge_fileds = new MergeFields();

  2. 隐式类初始化:

    public class Member
    {
       public string email_Address { get; set; }
       public string status { get; set; }
       public MergeFields merge_fields { get; set; }
    
       public Member(){
          merge_fields = new MergeFields();
       }
    }
    
  3. 使用第二种方法,您无需更改分配代码。

答案 1 :(得分:1)

你需要先初始化

person.merge_fileds = new MergeFields{CITY = cityTest};