Create Custom Constraints: C#: Use the TextStreamFactory: LISTING 1: This code shows how to use the TextStreamFactory.
You need to have some method that satisfies the expected behavior expressed by the delegate. Once you've done that, you need to instantiate that delegate and pass it to the CreateSequence() method when you are ready to create the sequence at runtime.
public class Person
{
public string LastName
{
get;
set;
}
public string FirstName
{
get;
set;
}
public override string ToString()
{
return string.Format("{0}, {1}", LastName, FirstName);
}
public static Person CreatePerson(string text)
{
// Split on spaces:
string[] tokens = text.Split(' ');
if (tokens.Length != 2)
throw new InvalidOperationException(
"Too many tokens for a person");
return new Person
{ LastName = tokens[1], FirstName = tokens[0] };
}
}
class Program
{
static void Main(string[] args)
{
TextStreamFactory<Person> Builder =
new TextStreamFactory<Person>(Console.In);
List<Person> peeps = new List<Person>();
peeps.AddRange(Builder.CreateSequence(
s => Person.CreatePerson(s)));
// testing:
foreach (Person p in peeps)
Console.WriteLine(p);
}
}