C#中GetType用法
时间: 2024-10-08 18:20:37 浏览: 39
在C#中,`GetType()`是一个静态方法,它用于获取当前对象的动态类型。这个方法属于所有.NET对象的默认成员,无论该对象是在运行时创建还是编译时指定其类型的。当你需要获取某个对象的实际类型,而不是它的声明类型时,`GetType()`非常有用。
以下是`GetType()`的一些常见用法:
1. **检查对象是否实现了某个接口**:
```csharp
object obj = ...; // 创建一个对象
Type type = obj.GetType();
if (type.GetInterfaces().Contains(typeof(IFoo))) // IFoo是接口名
Console.WriteLine(obj实现了IFoo接口);
```
2. **动态调用方法或访问属性**:
```csharp
dynamic dynObj = ...;
MethodInfo methodInfo = typeof(DerivedClass).GetMethod("MethodName");
var result = methodInfo.Invoke(dynObj, args); // 动态调用方法
PropertyInfo propInfo = type.GetProperty("PropertyName");
string value = propInfo.GetValue(dynObj); // 动态访问属性
```
3. **反射操作**:
可以利用`Type`对象做更深入的反射检查,如获取类型的信息、构造函数、字段等。
4. **泛型类型检查**:
```csharp
if (obj is List<T>) // T是类型参数
{
// 对List<T>类型的对象执行特定操作
}
```
阅读全文
相关推荐


















