GenericClassInherit
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class GenericClassInherit
{
//C# 编译器只允许将泛型参数隐式强制转换到 Object 或约束指定的类型
public interface ISomeInterface
{ }
class BaseClass
{ }
class MyClass<T> where T : BaseClass, ISomeInterface
{
void SomeMethod(T t)
{
ISomeInterface obj1 = t;
BaseClass obj2 = t;
object obj3 = t;
}
}
//编译器允许您将泛型参数显式强制转换到其他任何接口,但不能将其转换到类
class SomeClass
{ }
class MyClass1<T>
{
void SomeMethod(T t)
{
ISomeInterface obj1 = (ISomeInterface)t; //Compiles
//SomeClass obj2 = (SomeClass)t; //Does not compile
}
}
//使用临时的 Object 变量,将泛型参数强制转换到其他任何类型
class MyClass2<T>
{
void SomeMethod(T t)
{
object temp = t;
SomeClass obj = (SomeClass)temp;
}
}
//使用is和as运算符#region 使用is和as运算符
public class MyClass3<T>
{
public void SomeMethod(T t)
{
// if (t is int) { }
// if (t is LinkedList<int, string>) { }
// string str = t as string;
// if (str != null) { }
// LinkedList<int, string> list = t as LinkedList<int, string>;
// if (list != null) { }
}
}
}
}
posted on 2011-11-15 22:31 breakpoint 阅读(73) 评论(0) 编辑 收藏 举报