C# · 12月 22, 2021

c# – 如何使用字段类型?

我有一个方法来确定DataTable中列的最小值和最大值: public void GetMinMaxrange( DataTable data,string valueColumnName ){ var min = data.AsEnumerable().Min(m => m.Field<double>(valueColumnName)); var max = data.AsEnumerable().Max(m => m.Field<double>(valueColumnName));}

我想重构这个:

public void GetMinMaxrange( DataTable data,string valueColumnName ){ DataColumn column = data.Columns[valueColumnName]; var min = data.AsEnumerable().Min(m => m.Field<column.DataType>(valueColumnName)); var max = data.AsEnumerable().Max(m => m.Field<column.DataType>(valueColumnName));}

我需要确定数据类型并使用它而不是硬编码m.Field< double>.这该怎么做?

UPDATE
至于为什么我想计算最小和最大之间的差异

public static double/decimal/int GetMinMaxrange<T>(DataTable data,string valueColumnName) where T : IComparable<T> { DataColumn column = data.Columns[valueColumnName]; var min = data.AsEnumerable().Min(m => m.Field<T>(valueColumnName)); var max = data.AsEnumerable().Max(m => m.Field<T>(valueColumnName)); ; return max – min; }解决方法 简单地将其创建为通用应该有效: public void GetMinMaxrange<T>( DataTable data,string valueColumnName ) where T : IComparable<T>{ DataColumn column = data.Columns[valueColumnName]; var min = data.AsEnumerable().Min(m => m.Field<T>(valueColumnName)); var max = data.AsEnumerable().Max(m => m.Field<T>(valueColumnName));}

然后你将用作:

GetMinMaxrange<MyType>(dataTable,valueColumnName);