2015-02-24 58 views
2

,我要動態所有intialize表示ISET用一個HashSet,動態intitialize上構建類ISET <t>

下面是我如何與清單

var properties = GetType() 
       .GetProperties() 
       .Where(x => x.PropertyType.IsGenericType && 
          x.PropertyType.GetGenericTypeDefinition() == typeof(IList<>)) 
       .ToList(); 

      foreach (var property in properties) 
      { 
       // get T type of ISet 
       if (property.PropertyType.GetGenericArguments().Length > 1) continue; 
       var listElemType = property.PropertyType.GetGenericArguments()[0]; 
       if (listElemType == null) continue; 

       // create hashedset 
       var constructorInfo = typeof(List<>) 
        .MakeGenericType(listElemType) 
        .GetConstructor(Type.EmptyTypes); 

       //construct object 
       if (constructorInfo == null) continue; 
       var listInstance = (IList)constructorInfo.Invoke(null); 
       property.SetValue(this, listInstance); 
      } 

實現它爲IList的,但如果我嘗試對於ISet的同樣的事情,它不工作:(

 var properties = GetType() 
      .GetProperties() 
      .Where(x => x.PropertyType.IsGenericType && 
         x.PropertyType.GetGenericTypeDefinition() == typeof(ISet<>)) 
      .ToList(); 

     foreach (var property in properties) 
     { 
      // get T type of ISet 
      if (property.PropertyType.GetGenericArguments().Length > 1) continue; 
      var listElemType = property.PropertyType.GetGenericArguments()[0]; 
      if (listElemType == null) continue; 

      // create hashedset 
      var constructorInfo = typeof(HashSet<>) 
       .MakeGenericType(listElemType) 
       .GetConstructor(Type.EmptyTypes); 

      //construct object 
      if (constructorInfo == null) continue; 
    //============== HERE IS THE PROBLEM ============ 
      // var listInstance = (ISet)constructorInfo.Invoke(null); 
      // property.SetValue(this, listInstance); 
     } 

沒有ISet的像的IList ..如何實現它在這種情況下?

+2

這是什麼問題? – leppie 2015-02-24 05:46:21

+0

你爲什麼要施放'listInstance'爲什麼不把它留給'object'? – 2015-02-24 05:47:03

+2

@leppie他的問題是沒有非泛型的'ISet'接口,所以他不知道要將'listInstance'強制轉換爲什麼。 – 2015-02-24 05:47:42

回答

2

PropertyInfo.SetValue需要object,所以你不必投constructorInfo.Invoke(null)結果:

var listInstance = constructorInfo.Invoke(null); 
property.SetValue(this, listInstance);