Turpinot tēmu par sarakstiem un Generic iespējam, dažreiz ar minimālām koda rindiņām var uzrakstīt tipu pārveidošanas. Kā piemēru piedāvāju klasi darbam ar tagiem (tags - atslēgvārds, kuru pievieno rakstiem, lai to var grupēt)
Kods:
using
System;
using System.Collections.Generic;namespace Samples
{
/// <summary>
/// Tag class
/// </summary>
public class Tag
{
private readonly string text; /// <summary>
/// Initializes a new instance of the <see cref="Tag"/> class.
/// </summary>
/// <param name="text">The text.</param>
protected Tag (string text)
{
this.text = text;
}
/// <summary>
/// Gets the text.
/// </summary>
/// <value>The text.</value>
public string Text
{
get
{
return text;
}
}
/// <summary>
/// Gets the tags.
/// </summary>
/// <param name="text">The text.</param>
/// <returns></returns>
public static IEnumerable<Tag> ReadString (string text)
{
List<string> list = new List<string> (text.Split (';'));
return list.ConvertAll (new Converter<string, Tag> (CreateInstance));
}
private static Tag CreateInstance (string substring)
{
return new Tag (substring.Trim ());
}
/// <summary>
/// Stores the specified list.
/// </summary>
/// <param name="list">The list.</param>
public static void Store (IEnumerable<Tag> list)
{
// saglabā tagus
// ...
}
}
}
Izsaukums:
...
public static void Main (string[] args)
{
string tags = ".NET2.0;Collections;Generic";
IEnumerable<Tag> list = Tag.ReadString (tags);foreach (Tag tag in list)
{
Console.WriteLine (tag.Text);
}
Tag.Store (list);Console.ReadLine ();
}
...
Posted
Oct 04 2007, 05:20 PM
by
andrejs.mamontovs