2014-07-01 28 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 
    { 

    } 
相關問題