C#索引属性用法实例分析

本文实例讲述了C#索引属性的用法。分享给大家供大家参考。具体如下:

这里演示C#类如何声明索引属性以表示不同种类事物的类似数组的集合。

// indexedproperty.cs
using System;
public class Document
{
  // 以下类型允许文档的查看方式与字的数组一样:
  public class WordCollection
  {
    readonly Document document; // 包含文档
    internal WordCollection(Document d)
    {
      document = d;
    }
    // Helper 函数 -- 从字符“begin”开始在字符数组“text”中搜索
    // 字数“wordCount”。如果字数小于 wordCount,
    // 则返回 false。将“start”和
    // “length”设置为单词在文本中的位置和长度:
    private bool GetWord(char[] text, int begin, int wordCount, out int start, out int length)
    {
      int end = text.Length;
      int count = 0;
      int inWord = -1;
      start = length = 0;
      for (int i = begin; i <= end; ++i)
      {
        bool isLetter = i < end && Char.IsLetterOrDigit(text[i]);
        if (inWord >= 0)
        {
          if (!isLetter)
          {
            if (count++ == wordCount)
            {
              start = inWord;
              length = i - inWord;
              return true;
            }
            inWord = -1;
          }
        }
        else
        {
          if (isLetter)
            inWord = i;
        }
      }
      return false;
    }
    // 获取和设置包含文档中的字的索引器:
    public string this[int index]
    {
      get
      {
        int start, length;
        if (GetWord(document.TextArray, 0, index, out start, out length))
          return new string(document.TextArray, start, length);
        else
          throw new IndexOutOfRangeException();
      }
      set
      {
        int start, length;
        if (GetWord(document.TextArray, 0, index, out start, out length))
        {
          // 用字符串“value”替换位于 start/length 处的
          // 字:
          if (length == value.Length)
          {
            Array.Copy(value.ToCharArray(), 0, document.TextArray, start, length);
          }
          else
          {
            char[] newText =
              new char[document.TextArray.Length + value.Length - length];
            Array.Copy(document.TextArray, 0, newText, 0, start);
            Array.Copy(value.ToCharArray(), 0, newText, start, value.Length);
            Array.Copy(document.TextArray, start + length, newText, start + value.Length, document.TextArray.Length - start - length);
            document.TextArray = newText;
          }
        }
        else
          throw new IndexOutOfRangeException();
      }
    }
    // 获取包含文档中字的计数:
    public int Count
    {
      get
      {
        int count = 0, start = 0, length = 0;
        while (GetWord(document.TextArray, start + length, 0, out start, out length))
          ++count;
        return count;
      }
    }
  }
  // 以下类型允许文档的查看方式像字符的“数组”
  // 一样:
  public class CharacterCollection
  {
    readonly Document document; // 包含文档
    internal CharacterCollection(Document d)
    {
     document = d;
    }
    // 获取和设置包含文档中的字符的索引器:
    public char this[int index]
    {
      get
      {
        return document.TextArray[index];
      }
      set
      {
        document.TextArray[index] = value;
      }
    }
    // 获取包含文档中字符的计数:
    public int Count
    {
      get
      {
        return document.TextArray.Length;
      }
    }
  }
  // 由于字段的类型具有索引器,
  // 因此这些字段显示为“索引属性”:
  public WordCollection Words;
  public CharacterCollection Characters;
  private char[] TextArray; // 文档的文本。
  public Document(string initialText)
  {
    TextArray = initialText.ToCharArray();
    Words = new WordCollection(this);
    Characters = new CharacterCollection(this);
  }
  public string Text
  {
    get
    {
      return new string(TextArray);
    }
  }
}
class Test
{
  static void Main()
  {
    Document d = new Document(
      "peter piper picked a peck of pickled peppers. How many pickled peppers did peter piper pick?"
    );
    // 将字“peter”更改为“penelope”:
    for (int i = 0; i < d.Words.Count; ++i)
    {
      if (d.Words[i] == "peter")
        d.Words[i] = "penelope";
    }
    // 将字符“p”更改为“P”
    for (int i = 0; i < d.Characters.Count; ++i)
    {
      if (d.Characters[i] == 'p')
        d.Characters[i] = 'P';
    }
    Console.WriteLine(d.Text);
  }
}

希望本文所述对大家的C#程序设计有所帮助。

(0)

相关推荐

  • C#实现获取不同对象中名称相同属性的方法

    本文实例讲述了C#实现获取不同对象中名称相同属性的方法.分享给大家供大家参考.具体如下: [两个类] class demo1 { public string Name { get; set; } public int Age { get; set; } } class demo2 { public string Name { get; set; } public string Address { get; set; } } [初始化数据] List<object> list = new Lis

  • 详解C#中的属性和属性的使用

    属性 属性是一种成员,它提供灵活的机制来读取.写入或计算私有字段的值.属性可用作公共数据成员,但它们实际上是称为"访问器"的特殊方法.这使得可以轻松访问数据,还有助于提高方法的安全性和灵活性. 在此示例中,TimePeriod 类存储时间段.该类在内部以秒为单位存储时间,但是名为 Hours 的属性允许客户端以小时为单位指定时间. Hours 属性的访问器执行小时与秒之间的转换. class TimePeriod { private double seconds; public dou

  • C#实现ComboBox控件显示出多个数据源属性的方法

    本文实例讲述了C#实现ComboBox控件显示出多个数据源属性的方法.分享给大家供大家参考.具体如下: public partial class Form4 : Form { private Bitmap myBitmap; public Form4() { InitializeComponent(); DataTable dt = new DataTable(); DataColumn dc1 = new DataColumn("Name", typeof(System.String

  • C#类中属性与成员变量的使用小结

    属性实际上和成员变量没什么区别,属性代表类的某种特征, 让人更好理解而已. 使用中注意问题:1.属性名和变量名不能相同, 2.一般变量都是private,属性都是public的,属性用于给类外调用,变量限于类内使用,感觉封装性体现得要好些 3.属性必须和一个变量相联系,而这个变量必须要在类中定义.如果不定义,用成如下方法: 复制代码 代码如下: public int b //定义一个属性b  {      get   {    return b;   }   set   {    b = val

  • C#利用反射来判断对象是否包含某个属性的实现方法

    本文实例展示了C#利用反射来判断对象是否包含某个属性的实现方法,对于C#程序设计人员来说有一定的学习借鉴价值. 具体实现代码如下: /// <summary> /// 利用反射来判断对象是否包含某个属性 /// </summary> /// <param name="instance">object</param> /// <param name="propertyName">需要判断的属性</par

  • C#中属性和成员变量的区别说明

    一个类,有时候搞不清楚到底用成员变量还是属性. 如: 成员变量 public   string   Name; 或者用属性 private   string   name public   string   Name{         get         {                 return   name;         }         set         {                 name   =   value;         } } 属性与成员变量类似

  • C#类中的属性使用总结(详解类的属性)

    复制代码 代码如下: private int dd;  public int dd  {      get{ return xx*3;}      set{ xx = value/3;}  } 没有set的属性是一种只读属性,没有get的访问器是一种只写属性.(1) get访问器用来返回字段或者计算 并返回字段,它必须以return或者throw终结. 复制代码 代码如下: private string name;  public string Name  {      get      { 

  • C#中使用反射遍历一个对象属性及值的小技巧

    总结: 对应某个类的实例化的对象tc, 遍历获取所有属性(子成员)的方法(采用反射): 复制代码 代码如下: Type t = tc.GetType();//获得该类的Type //再用Type.GetProperties获得PropertyInfo[],然后就可以用foreach 遍历了 foreach (PropertyInfo pi in t.GetProperties()) {     object value1 = pi.GetValue(tc, null));//用pi.GetVal

  • C#属性(Attribute)用法实例解析

    属性(Attribute)是C#程序设计中非常重要的一个技术,应用范围广泛,用法灵活多变.本文就以实例形式分析了C#中属性的应用.具体入戏: 一.运用范围 程序集,模块,类型(类,结构,枚举,接口,委托),字段,方法(含构造),方法,参数,方法返回值,属性(property),Attribute [AttributeUsage(AttributeTargets.All)] public class TestAttribute : Attribute { } [TestAttribute]//结构

  • 轻松学习C#的属性

    属性是提供对对象或类的特性进行访问的成员.属性提供功能强大的方法将声明信息与C#代码(类型,方法,属性等)相关联.属性的设置包括字符串的长度,字体的大小,窗口的焦点,用户的名字等.         使程序员可以创造新的声明信息的种类,称为属性.属性是对现实世界中实体特征的抽象,是为访问自定义类型的注释信息提供通用的访问方式.属性使类能够以一种公开的思路方法获取和设置值,同时隐藏实现或验证代码.C#的属性具有保护功能,可以让用户像访问域一样访问属性.         属性包括字符串各种信息和字符串

  • C#实现ProperTyGrid自定义属性的方法

    本文实例讲解了C#实现ProperTyGrid自定义属性的方法,分享给大家供大家参考.具体方法如下: 一般来说,C#如果要实现自定义属性必须要需要实现接口ICustomTypeDescriptor,具体实现方法如下: // 摘要: // 提供为对象提供动态自定义类型信息的接口. public interface ICustomTypeDescriptor 示例如下: /// <summary> /// 自定义属性对象 /// </summary> public class MyAt

随机推荐