如何使用GetType获取类的类型

时间:2018-12-20 17:52:49

标签: 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
有没有可用的方法或财产?

1 个答案:

答案 0 :(得分:3)

尝试Type.FullName获得所需的内容- https://docs.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;
   }
}