2013-02-15 8 views
5

Tôi có một lớp học với một tài sản IEnumerable<T>. Làm cách nào để tạo một phương thức chung để tạo một List<T> mới và gán thuộc tính đó?Tạo danh sách chung <T> với sự phản ánh

IList list = property.PropertyType.GetGenericTypeDefinition() 
    .MakeGenericType(property.PropertyType.GetGenericArguments()) 
    .GetConstructor(Type.EmptyTypes); 

Tôi không biết đâu là loại T có thể được bất cứ điều gì

+3

Không chắc chắn những gì bạn có nghĩa là, có thể giúp bạn không chỉ sử dụng 'IEnumerable.ToList()' –

+0

biết chính xác là bạn Tring để làm, tạo ra một 'Danh sách ' dạng 'IEnumerable '?? –

+0

tôi cần tạo danh sách trống với loại thuộc tính – rkmax

Trả lời

16

Giả sử bạn biết tên tài sản, và bạn biết điều đó là một IEnumerable<T> thì chức năng này sẽ đặt nó vào một danh sách các loại tương ứng:

public void AssignListProperty(Object obj, String propName) 
{ 
    var prop = obj.GetType().GetProperty(propName); 
    var listType = typeof(List<>); 
    var genericArgs = prop.PropertyType.GetGenericArguments(); 
    var concreteType = listType.MakeGenericType(genericArgs); 
    var newList = Activator.CreateInstance(concreteType); 
    prop.SetValue(obj, newList); 
} 

Xin lưu ý rằng phương pháp này không kiểm tra loại hoặc xử lý lỗi. Tôi để nó như một bài tập cho người dùng.

+0

Tôi đã hoàn toàn quên Activator.CreateInstance, xử lý lỗi được thực hiện;) – rkmax

1
using System; 
using System.Collections.Generic; 

namespace ConsoleApplication16 
{ 
    class Program 
    { 
     static IEnumerable<int> Func() 
     { 
      yield return 1; 
      yield return 2; 
      yield return 3; 
     } 

     static List<int> MakeList() 
     { 
      return (List<int>)Activator.CreateInstance(typeof(List<int>), Func()); 
     } 

     static void Main(string[] args) 
     { 
      foreach(int i in MakeList()) 
      { 
       Console.WriteLine(i); 
      } 
     } 
    } 
} 
+0

Tại sao không chỉ sử dụng 'Func(). ToList()' –

+0

T ở đâu? Không phải là chung chung. –