c# - 如何使用 GetType 获取类的类型

标签 c# reflection

我在这里使用 GetType() 来获取 eventData 的类型,如下所示,

public EventDescriptor(Guid id, IEvent eventData)
{
   AggregateId = id;
   EventData = eventData;
   EventType = eventData.GetType().AssemblyQualifiedName;
}

返回:

 "EventType":  
 "Shared.Events.EntityCreatedEvent`1[[Shared.Model.Dto.EntityDto, Shared,  
  Version=1.0.6928.25697, Culture=neutral, PublicKeyToken=null]], Shared,  
  Version=1.0.6928.25697, Culture=neutral, PublicKeyToken=null"

我怎样才能从上面只得到 Shared.Model.Dto.EntityDto
有没有可用的方法或属性?

最佳答案

试试 Type.FullName 来获得你需要的 - https://learn.microsoft.com/de-de/dotnet/api/system.type.fullname?view=netframework-4.7.2

所以在你的情况下 -

public EventDescriptor(Guid id, IEvent eventData)
 {
   AggregateId = id;
   EventData = eventData;
   EventType = eventData.GetType().FullName;
}

如果你想提取 IEvent 实例的泛型参数的类型,你可以这样做 -

public EventDescriptor(Guid id, IEvent eventData)
 {
   AggregateId = id;
   EventData = eventData;
   if (!eventData.GetType().IsGenericType)
   {
       EventType = eventData.GetType().FullName;
   }
   else
   {
       // notice - this assumes we can take the FIRST generic argument, we don't check for others here
       EventType = eventData.GetType().GetGenericArguments().First().FullName;
   }
}

关于c# - 如何使用 GetType 获取类的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53873782/

相关文章:

java - JSP页面如何找到正确的参数 setter

c# - 如何从调用栈中反射(reflect)C#显式接口(interface)实现?

c# - 使用反射和表达式的自动列映射

c# - C# 开发人员可以从 Objective-C 中学到什么?

c# - 返回一个字符串列表作为 JSONResult

c# - 从 .NET 客户端对 Axis2/JAX-WS Web 服务使用多态调用

c# - 如何使用反射获取对象的属性?

c# - 怎么画十字?

c# - "Activity Pointer"CRM 2011 中不允许创建/更新方法

Scala 2.10 反射 : Creating an Array from a type