好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#中Type的功能及使用范围

C#中Type的功能及使用范围

在 C# 中,Type 类(位于 System 命名空间)是反射(Reflection)的核心类型之一,用于表示类型的元数据。通过 Type 对象,可以在运行时?动态获取类型信息?(如类、接口、结构体、枚举等的定义),并执行与类型相关的操作。以下是它的主要用途和示例:

?1. 获取类型的基本信息?

?类型名称、命名空间、程序集等?:

Type type = typeof(string);

Console.WriteLine(type.Name);        // 输出:String

Console.WriteLine(type.Namespace);    // 输出:System

Console.WriteLine(type.Assembly.FullName); // 程序集信息

?2. 检查类型的结构?

?判断类型是类、接口、值类型等?:

Type type = typeof(int);

Console.WriteLine(type.IsClass);      // 输出:False(int 是值类型)

Console.WriteLine(type.IsValueType);  // 输出:True

?检查继承关系?:

Type type = typeof(ArgumentException);

Console.WriteLine(type.IsSubclassOf(typeof(Exception))); // 输出:True

?3. 动态访问成员?

通过 Type 可以获取类型的成员(方法、属性、字段、事件等),并动态调用它们:

?获取方法并调用?:

Type type = typeof(Math);

MethodInfo method = type.GetMethod("Sqrt", new[] { typeof(double) });

double result = (double)method.Invoke(null, new object[] { 4.0 });

Console.WriteLine(result); // 输出:2

?获取属性并读写值?:

object obj = new StringBuilder("Hello");

Type type = obj.GetType();

PropertyInfo prop = type.GetProperty("Length");

int length = (int)prop.GetValue(obj);

Console.WriteLine(length); // 输出:5

?4. 动态创建对象?

?通过无参构造函数创建实例?:

Type type = typeof(StringBuilder);

object instance = Activator.CreateInstance(type);

?通过有参构造函数创建实例?:

Type type = typeof(StringBuilder);

ConstructorInfo ctor = type.GetConstructor(new[] { typeof(string) });

object instance = ctor.Invoke(new object[] { "Test" });

?5. 泛型类型操作?

?判断是否是泛型类型?:

Type listType = typeof(List<>);

Console.WriteLine(listType.IsGenericType); // 输出:True

?创建泛型实例?:

Type openType = typeof(List<>);

Type closedType = openType.MakeGenericType(typeof(int));

object list = Activator.CreateInstance(closedType);

?6. 特性(Attribute)检查?

?获取类型上的自定义特性?:

[Serializable]

public class MyClass { }

Type type = typeof(MyClass);

bool isSerializable = type.IsDefined(typeof(SerializableAttribute), false);

Console.WriteLine(isSerializable); // 输出:True

?7. 类型发现?

?从程序集中加载所有类型?:

Assembly assembly = Assembly.GetExecutingAssembly();

Type[] types = assembly.GetTypes();

foreach (Type t in types)

{

    Console.WriteLine(t.FullName);

}

?如何获取 Type 对象??

?typeof 运算符?:编译时已知类型。

Type type = typeof(int);

?GetType() 方法?:通过实例获取运行时类型。

string s = "Hello";

Type type = s.GetType(); // 返回 String 类型

?Type.GetType("类型全名")?:通过类型全名字符串获取。

Type type = Type.GetType("System.Int32");

?典型应用场景?

?反射?:动态加载程序集、调用方法、创建对象。

?序列化/反序列化?:根据类型元数据处理对象。

?依赖注入框架?:根据类型解析依赖。

?单元测试框架?:发现测试类和方法。

?插件系统?:动态加载外部类型。

?注意事项?

?性能?:反射操作(如 Invoke)比直接调用慢,避免高频使用。

?安全性?:反射可能绕过访问修饰符(需适当权限)。

通过 Type,C# 可以在运行时实现高度动态的行为,是框架开发、工具库和复杂系统的重要基础。


查看更多关于C#中Type的功能及使用范围的详细内容...

  阅读:26次