C# 开放类型与封闭类型
2016-03-03 21:15
423 查看
开放类型 具有泛型类型参数的类型
封闭类型 为所有类型参数都传递了实际的数据类型
using System;
using System.Collections.Generic;
namespace TypeObjectDemo
{
internal sealed class DictionaryStringKey<TValue>:Dictionary<string, TValue>{ }
class Program
{
static void Main(string[] args)
{
object o = null;
// Dictionary<,>为开放类型,有2个类型参数
Type t = typeof(Dictionary<,>);
// 尝试创建该类型的实例(失败)
o = CreateInstance(t);
Console.WriteLine();
// DictionaryStringKey<>为开放类型,有1个参数
t = typeof(DictionaryStringKey<>);
// 尝试创建该类型的实例(失败)
o = CreateInstance(t);
Console.WriteLine();
// DictionaryStringKey<Guid>就封闭类型
t = typeof(DictionaryStringKey<Guid>);
// 尝试创建(成功)
o = CreateInstance(t);
//证明能工作
Console.WriteLine(" object type = {0}", o.GetType());
Console.ReadKey();
}
private static object CreateInstance(Type t)
{
object o = null;
try
{
o = Activator.CreateInstance(t);
Console.WriteLine("builded {0}'s instance.", t.ToString());
}
catch(ArgumentException e)
{
Console.WriteLine(e.Message);
}
return o;
}
}
}输出如下:
封闭类型 为所有类型参数都传递了实际的数据类型
using System;
using System.Collections.Generic;
namespace TypeObjectDemo
{
internal sealed class DictionaryStringKey<TValue>:Dictionary<string, TValue>{ }
class Program
{
static void Main(string[] args)
{
object o = null;
// Dictionary<,>为开放类型,有2个类型参数
Type t = typeof(Dictionary<,>);
// 尝试创建该类型的实例(失败)
o = CreateInstance(t);
Console.WriteLine();
// DictionaryStringKey<>为开放类型,有1个参数
t = typeof(DictionaryStringKey<>);
// 尝试创建该类型的实例(失败)
o = CreateInstance(t);
Console.WriteLine();
// DictionaryStringKey<Guid>就封闭类型
t = typeof(DictionaryStringKey<Guid>);
// 尝试创建(成功)
o = CreateInstance(t);
//证明能工作
Console.WriteLine(" object type = {0}", o.GetType());
Console.ReadKey();
}
private static object CreateInstance(Type t)
{
object o = null;
try
{
o = Activator.CreateInstance(t);
Console.WriteLine("builded {0}'s instance.", t.ToString());
}
catch(ArgumentException e)
{
Console.WriteLine(e.Message);
}
return o;
}
}
}输出如下:
相关文章推荐
- C#成魔之路<1>Windows 应用程序高级控件(1)
- 理解C# 中委托的含义
- c、c#---计时器
- C#开发ftp客户端遇到550错误
- C#成魔之路<开篇>
- 《C#高级编程》读书笔记
- C# WinForm制作电子琴键盘
- C#开发之问题汇总-项目移动路径后编译或者发布错误
- 在C#中将String转换成Enum:
- C#.NET扩展方法
- C# Socket编程 同步以及异步通信
- 在C#中主线程和子线程如何实现互相传递数据
- C# 读取Log4net 日志文件
- C#日期格式转换大全
- NPOI导出Excel (C#) 踩坑 之--The maximum column width for an individual cell is 255 charaters
- C#开发之问题汇总-NetFramework的版本选择
- C#从零开始——生成dll文件并调用
- C#开发之问题汇总-vs运行正常,服务器IIS上报未能加载程序集
- C# 文件压缩与解压(ZIP格式)
- C#实现多选项卡的浏览器控件