2013-08-21 20 views
5

मैं एक डेटाटेबल जेनरेट करने के लिए एक विधि लिख रहा हूं जो एक सामान्य आईनेमरेबल डेटासेट करता है। मैं, क्षेत्र थेरेस अगर कोई मूल्य पर एक डिफ़ॉल्ट मान सेट करने के लिए कोशिश कर रहा हूँ नीचे कोड के साथ:यह कोड संकलित क्यों नहीं है?

The type or namespace name 'typeAux', could not be found (are you missing a using directive or an assembly reference?)

क्यों:

private void createTable<T>(IEnumerable<T> MyCollection, DataTable tabela) 
     { 
      Type tipo = typeof(T); 

      foreach (var item in tipo.GetFields()) 
      { 
       tabela.Columns.Add(new DataColumn(item.Name, item.FieldType)); 
      } 

      foreach (Pessoa recordOnEnumerable in ListaPessoa.listaPessoas) 
      { 
       DataRow linha = tabela.NewRow(); 

       foreach (FieldInfo itemField in tipo.GetFields()) 
       { 
        Type typeAux = itemField.GetType(); 

        linha[itemField.Name] = 
         itemField.GetValue(recordOnEnumerable) ?? default(typeAux); 

       } 
      } 
     } 

यह इस त्रुटि फेंक रहा है? फ़ंक्शन "डिफ़ॉल्ट (प्रकार)" फ़ंक्शन को उस प्रकार के लिए डिफ़ॉल्ट मान वापस नहीं करना चाहिए?

+3

'डिफ़ॉल्ट()' एक नामित प्रकार, नहीं एक 'Type' संदर्भ की आवश्यकता है। उदाहरण के लिए, 'डिफ़ॉल्ट (int) '। – recursive

उत्तर

1

कैसे मूल्य प्रकार के लिए संदर्भ प्रकार के लिए अशक्त और Activator.CreateInstance लौटने के बारे में

public static object GetDefault(Type type) 
{ 
    if(type.IsValueType) 
    { 
     return Activator.CreateInstance(type); 
    } 
    return null; 
} 

संदर्भ: Programmatic equivalent of default(Type)

+0

अच्छा है, धन्यवाद –

0

default कथन System.Type के साथ काम नहीं करता है।

linha[itemField.Name] = itemField.GetValue(recordOnEnumerable) ?? DBNull.Value; 

यदि मान null है, null (जो, एक DataRow में, DBNull.Value है) के लिए परिणाम की स्थापना:

कहा जा रहा है, यह है कि छोड़ने के लिए बाहर, और सीधे DBNull का उपयोग अधिक उपयुक्त लग रहा है उचित लगता है।

+0

लेकिन क्या यह आवश्यक है कि int, बूलियन इत्यादि जैसे प्रकारों को Nullables की तरह घोषित किया जा सके? ... –

+0

@WilnerAvila No - 'itemField.GetValue' वास्तव में शून्य को वापस कर देगा यदि मान वास्तव में शून्य था। Int, bool, आदि के साथ कभी नहीं हो सकता –

संबंधित मुद्दे