using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
Person p = new Person("Bruce", 30);
Console.WriteLine("PrintXML : ");
PrintXML(p);
Console.WriteLine("PrintTwo : ");
PrintTwo("Time", DateTime.Now);
StringBuilder sb = new StringBuilder();
//p = CreateGenericNew(p); // without public non-parameter constructor, not allowed
sb = CreateGenericNew(sb); // it's ok
Console.WriteLine("Object is null : {0}", sb == null);
p = CreateGenericDefault(p); // it's ok
sb = CreateGenericDefault(sb); // it's ok
Console.WriteLine("Object is null : {0}", sb == null);
Console.Read();
}
static void PrintXML<T>(T obj) where T : ISerializeXML
{
Console.WriteLine(obj.ToXML());
}
static void PrintTwo<T, V>(T key, V value)
{
Console.WriteLine("{0}={1}", key, value);
}
static T CreateGenericNew<T>(T obj) where T : new()
{
return new T();
}
static T CreateGenericDefault<T>(T obj)
{
return default(T);
}
}
interface ISerializeXML
{
string ToXML();
}
class Person : ISerializeXML
{
public string Name { get; private set; }
public int Age { get; private set; }
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
#region ISerializeXML 成員
public string ToXML()
{
return string.Format(
@"<person><name>{0}</name><age>{1}</age></person>",
this.Name,
this.Age
);
}
#endregion
public override string ToString()
{
return string.Format("{0},{1}", this.Name, this.Age);
}
}
}
output:
PrintXML : <person><name>Bruce</name><age>30</age></person> PrintTwo : Time=2010/4/16 00:46:28 Object is null : False Object is null : Truesee also:
http://msdn.microsoft.com/en-us/library/ms379564%28VS.80%29.aspx
http://proglab-justin.blogspot.com/2010/01/net-genericdefaulttnew-t_23.html