/// <summary>
/// 接口
/// </summary>
public interface IType
{
void ShowTypeInfo();
}
/// <summary>
/// 基类
/// </summary>
public class BaseType
{
public virtual void ShowTypeInfo()
{
Console.WriteLine(this.GetType().ToString());
}
}
/// <summary>
/// 接口实现类
/// </summary>
public class ImpIType : IType
{
public void ShowTypeInfo()
{
Console.WriteLine(this.GetType().ToString());
}
}
/// <summary>
/// 基类继承类
/// </summary>
public class SubType : BaseType
{
}
/// <summary>
/// 限定当前参数类型必须是值类型
/// </summary>
/// <typeparam name="T"></typeparam>
public class ValueType<T> where T : struct
{
public void ShowTypeInfo()
{
Console.WriteLine(this.GetType().ToString());
}
}
/// <summary>
/// 限定当前类型参数类型必须是引用类型
/// </summary>
/// <typeparam name="T"></typeparam>
public class RefType<T> where T : class
{
public void ShowTypeInfo()
{
Console.WriteLine(this.GetType().ToString());
}
}
/// <summary>
/// 限定当前参数类型必须有一个无参构造器
/// </summary>
/// <typeparam name="T"></typeparam>
public class NewType<T> where T : new()
{
public void ShowTypeInfo()
{
Console.WriteLine(this.GetType().ToString());
}
}
/// <summary>
/// 限定当前参数类型 必须是当前类 或者当前类为基类的类
/// </summary>
/// <typeparam name="T"></typeparam>
public class SameBaseType<T> where T : BaseType
{
public void ShowTypeInfo()
{
Console.WriteLine(this.GetType().ToString());
}
}
/// <summary>
/// 限定当前参数类型必须实现指定接口
/// </summary>
/// <typeparam name="T"></typeparam>
public class ImpInterfaceType<T> where T : IType
{
public void ShowTypeInfo()
{
Console.WriteLine(this.GetType().ToString());
}
}
/// <summary>
/// 多种约束
/// </summary>
/// <typeparam name="T"></typeparam>
public class ComplexType<T> where T : IType, new()
{
public void ShowTypeInfo()
{
Console.WriteLine(this.GetType().ToString());
}
}
3.测试
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please input a line to continue or X to exit!");
string input;
while ((input = Console.ReadLine()) != "X")
{
switch (input)
{
case "1":
ValueType<int> @int = new ValueType<int>();
@int.ShowTypeInfo();
break;
case "2":
RefType<BaseType> @BaseType = new RefType<BaseType>();
@BaseType.ShowTypeInfo();
break;
case "3":
NewType<double> @double = new NewType<double>();
@double.ShowTypeInfo();
break;
case "4":
SameBaseType<SubType> @SubType = new SameBaseType<SubType>();
@SubType.ShowTypeInfo();
break;
case "5":
ImpInterfaceType<ImpIType> @ImpIType = new ImpInterfaceType<ImpIType>();
ImpIType.ShowTypeInfo();
break;
case "6":
ComplexType<ImpIType> complexType = new ComplexType<ImpIType>();
complexType.ShowTypeInfo();
break;
default:
break;
}
}
}
}
测试截图: