2014-07-01 97 views
1

我试图使用模型绑定提供程序对模型进行绑定。如何获得某个类的<T><T>当某个类通过某个类型时

GetBinder方法被击中我想基于什么是传递给服务一个模型粘合剂。

我有一个通用模型IBaseModel<T> where T : IEntity

我可以从类型中获取BaseModel,但我真正想要的是BaseModel<T>上的<T>,它是IEntity

public IModelBinder GetBinder(Type modelType) 
{ 
    Type baseModel = modelType.GetInterface(typeof(IBaseModel<>).Name); 

    if (baseModel != null) 
    { 
     if (baseModel.IsGenericType) 
     { 
      //want to get <T> (IEntity) here.   
     } 
    } 

在此先感谢

+2

[反思可能重复 - 开始从一般的参数System.Type实例](http://stackoverflow.com/questions/293905/reflection-getting-the-generic-parameters-from-a-system-type-in​​stance) – Chris

+0

感谢克里斯那正是我需要的。我不确定如何说出我的问题,这就是为什么答案通过了我。 – Hemslingo

+0

这很酷。正如你所说不容易知道要搜索什么。我知道他们被称为通用参数,因此能够立即到达那里。 :) – Chris

回答

0

我明白,你想你可以试试这个泛型参数的类型:

public static Type GetBinder(Type modelType) 
    { 
     Type baseModel = modelType.GetInterface(typeof (IBaseModel<>).Name); 

     if (baseModel != null) 
     { 
      if (baseModel.IsGenericType) 
      { 
       var interfacesTypes = modelType.GetInterfaces(); 
       var typeGeneric = interfacesTypes.FirstOrDefault(x => x.IsGenericTypeDefinition); 
       if (typeGeneric != null) 
       { 
        return typeGeneric.GetGenericArguments().First(); 
       } 

      } 
     } 
     return null; 
    } 

    public interface IBaseModel<T> where T : IEntity 
    { 

    } 

    public class Musica : IBaseModel<Artista> 
    { 

    } 

    public class Artista : IEntity 
    { 

    } 
相关问题