2011-07-16 84 views
3

我有一个对象,我使用反射创建了一个实体(T)。该对象是我实现的一个表。它拥有的列清单,我使用反射从实体中提取它们的属性:强制转换原始类型为可空对象

public class Generic_Table<T> : Table 
    {   
     ...// in ctor 
     type = this.GetType().GetGenericArguments()[0]; // type of T 
     BuildColumns(type); 

     private void BuildColumns(Type type) 
     { 
      PropertyInfo[] properties = type.GetProperties(); 

      Columns = new KeyValuePair<string, Type>[properties.Count()]; 
      int i = 0; 
      foreach (PropertyInfo property in properties) 
      { 
       Columns[i++] = new KeyValuePair<string, Type>(property.Name, property.PropertyType);     
      } 
     } 

我正在寻找一种方式来投的PropertyType值作为可空类型,所以在列Type值会如果例如int?的值为int,则其值。

+0

我需要获得15个声望才能接受答案 所以我真的不能工作呢。 .. –

+0

好吧,iv'e标记所有帮助完整答案..我不知道为什么它说100%现在.. 我没有标记他们所有,但我没有标记一个我曾得到答案 –

回答

3

这将你需要的东西:

Type nullableType = typeof(Nullable<>).MakeGenericType(property.PropertyType); 

MakeGenericType方法接受的泛型类型参数的参数数组。查看文档了解更多信息:

此外,这篇文章有类似的东西一个很好的例子,你在这里做什么:

+0

谢谢男人 ,做到了。 –

相关问题