【问题标题】:Why isn't this code compiling?为什么这段代码不编译?
【发布时间】:2013-08-21 00:23:55
【问题描述】:

我正在编写一个方法来生成一个将通用 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); 

                }
            }
        }

它抛出了这个错误:

找不到类型或命名空间名称“typeAux”(您是否缺少 using 指令或程序集引用?)

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

【问题讨论】:

  • default() 需要命名类型,而不是 Type 引用。例如,default(int)

标签: c# .net generics types


【解决方案1】:

如何为引用类型返回 null,为值类型返回 Activator.CreateInstance

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

参考:Programmatic equivalent of default(Type)

【讨论】:

    【解决方案2】:

    default 语句不适用于System.Type

    话虽如此,将其省略似乎更合适,直接使用DBNull

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

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

    【讨论】:

    • 但这是否需要将 int、boolean 等类型声明为 Nullables?...
    • @WilnerAvila 否 - itemField.GetValue 只会在值实际上为 null 时返回 null。 int、bool 等永远不会发生
    猜你喜欢
    • 2012-07-06
    • 2013-08-08
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 2011-11-27
    • 2014-09-14
    • 1970-01-01
    相关资源
    最近更新 更多