为什么这个代码不编译?

时间:2021-12-27 03:13:19

I'm writing a method to generate a DataTable taking as datasource a generic IEnumerable. I am trying to set a default value on the field if theres no value, with the code below:

我正在编写一个方法,以一个通用的IEnumerable作为数据源生成一个DataTable。如果没有值,我尝试在字段上设置一个默认值,代码如下:

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); 

                }
            }
        }

It's throwing this error:

把这个错误:

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

无法找到类型或名称空间名称“typeAux”(是否缺少使用指令或程序集引用?)

Why? Shouldn't the function "Default(Type)" return a default value for that type?

为什么?函数“Default(Type)”不应该为该类型返回一个默认值吗?

2 个解决方案

#1


1  

How about returning null for reference types and Activator.CreateInstance for value types

如何为引用类型和激活器返回null。CreateInstance除外的值类型

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

Reference: Programmatic equivalent of default(Type)

引用:默认的编程等效项(类型)

#2


0  

The default statement doesn't work with System.Type.

默认语句不适用于System.Type。

That being said, it seems more appropriate to leave that out, and use DBNull directly:

话虽如此,似乎还是应该把它排除在外,直接使用DBNull:

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

If the value is null, setting the result to null (which, in a DataRow, is DBNull.Value) seems appropriate.

如果值为null,那么将结果设置为null(在DataRow中,这个值是DBNull.Value)似乎是合适的。

#1


1  

How about returning null for reference types and Activator.CreateInstance for value types

如何为引用类型和激活器返回null。CreateInstance除外的值类型

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

Reference: Programmatic equivalent of default(Type)

引用:默认的编程等效项(类型)

#2


0  

The default statement doesn't work with System.Type.

默认语句不适用于System.Type。

That being said, it seems more appropriate to leave that out, and use DBNull directly:

话虽如此,似乎还是应该把它排除在外,直接使用DBNull:

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

If the value is null, setting the result to null (which, in a DataRow, is DBNull.Value) seems appropriate.

如果值为null,那么将结果设置为null(在DataRow中,这个值是DBNull.Value)似乎是合适的。