首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

关于字符串索引有关问题

2012-11-04 
关于字符串索引问题using Systemusing System.Collections.Genericusing System.Linqusing System.Text

关于字符串索引问题
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace indexer
{
  public class listboxtest

  {
  private int ctr = 0;
  private string[] strings;
   
  public listboxtest(params string[] initialstrings)
  {
  strings = new string[11];
   
  foreach (string s in initialstrings)
  {
  strings[ctr++] = s;
  Console.WriteLine("索引1为:{0}", ctr);
  }
  }
  public void add(string thestring)
  {
  if (ctr >= strings.Length)
  {
  //处理错误索引
  }
  else
  strings[ctr++] = thestring;
  Console.WriteLine("索引为:{0}", ctr);
  }
   
  public string this[int index]
  {

   
  get 
  {
   
  if (index < 0 || index >= strings.Length)
  {
  return strings[6];
  }
  else
  return strings[index];
   
  }
  set
  {
  if (index >= strings.Length)
  {
  //处理错误
  }
  else
  {
  strings[index] = value;
  // if (ctr < index + 1)
  // ctr = index + 1;
  }
  }
  }
  private int findstring(string searchstring)
  {
  int t = 3;
  for (int i = 0; i < strings.Length; i++)
   
  if (strings[i].StartsWith(searchstring))
  return i; 
   
  return t;
  }
  public string this[string index]
  {
  get
  {
  if (index.Length == 0)
  { 
  //处理错误
  }
  return this[findstring(index)];
  }
  set
  {
  if (findstring(index) < 0)
  { 
  //处理错误
  }
  else
  strings[findstring(index)] = value;
  }
  }
  public int getnumentries()
  {
  return ctr;
  }
  }
  class Program
  {
  static void Main(string[] args)
  {
  listboxtest lbt=new listboxtest("hello","world");
  lbt.add("who");
  lbt.add("is");
  lbt.add("douglas");
  lbt.add("adams");
  string subst = "universe";
  lbt[1] = subst;
  lbt["dd"] = "goodbye";  
  for (int i = 0; i <= lbt.getnumentries(); i++)
  {


  Console.WriteLine("lbt[{0}] {1}ctr{2}", i, lbt[i], lbt.getnumentries());
  }
  }
  }
}
--------------------------------------------------
为什么会提示未处理的异常,未将对象引用设置到对象的实例。我这句lbt["dd"] = "goodbye";  
应该返回t啊,怎么没有返回呢?本来应该是lbt[t]="goodbye"才对,真奇怪,望高人指点,谢谢!

[解决办法]
lbt["dd"]为null了吧。
设置个断点,看的清清楚楚。
[解决办法]
你的strings数组大小是11个而且没有初始化,但是你只给了六个值,从strings[6]开始数组的值就为null。
所以这句 if (strings[i].StartsWith(searchstring))就会出现未将对象引用设置到对象的实例
的问题。

[解决办法]
为什么会提示未处理的异常,未将对象引用设置到对象的实例
==>
有对象为 null
断点进入看下

热点排行