Skip to main content
 首页 » 编程设计

c#之显式 Int 转换溢出

2024年02月23日20dflying

问题

当我将值传递给 int 时值超过 int 最大值的变量, int 的值变量变为 0 .

背景

我使用以下步骤来检索我的数据。我不会在不抛出异常的情况下使用任何 try-catch block 。

第一步

在我的WCF 服务 中,我检索了一个 DataTable使用 IBM.Data.DB2.iSeries.iDB2DataAdapter.Fill(DataSet)

第二步

然后我转换 DataTable至 List<T>使用代码:

public static List<T> DataTableToList<T>(DataTable dt) 
{ 
    List<T> tableEntity = new List<T>(); 
 
    foreach (DataRow row in dt.Rows) 
    { 
        T rowEntity = Activator.CreateInstance<T>(); 
 
        rowEntity.GetType().GetProperties().Where(o => dt.Columns.OfType<DataColumn>() 
            .Select(p => p.ColumnName).Contains(o.Name)).ToList() 
            .ForEach(o => o.SetValue(rowEntity, row[o.Name], null)); 
 
        tableEntity.Add(rowEntity); 
    } 
 
    return tableEntity; 
} 

类型:

public class Client 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
} 

第三步

我使用 WCF 服务方法返回它:

[OperationContract] 
public string GetClients() 
{ 
    List<Client> clients = new DB().RetrieveClients(); 
    return Tools.SerializeObjectToXML<List<Client>>(clients); 
} 

使用序列化的辅助方法:

public static string SerializeObjectToXML<T>(T item) 
{ 
    XmlSerializer xs = new XmlSerializer(typeof(T)); 
    using (StringWriter writer = new StringWriter()) 
    { 
        xs.Serialize(writer, item); 
        return writer.ToString(); 
    } 
} 

第四步

然后在 Client Application 中,我使用 WSHttpBinding 的默认绑定(bind)和代码从 Service Reference 检索它:

List<Client> clients = Tools.DeserializeXMLToObject<List<Client>>(new SomeServiceClient().GetClients()); 

使用反序列化的辅助方法:

public static T DeserializeXMLToObject<T>(string xmlText) 
{ 
    if (string.IsNullOrEmpty(xmlText)) return default(T); 
    XmlSerializer xs = new XmlSerializer(typeof(T)); 
    using (MemoryStream memoryStream = new MemoryStream(new UnicodeEncoding().GetBytes(xmlText))) 
    using (XmlTextReader xsText = new XmlTextReader(memoryStream)) 
    { 
        xsText.Normalization = true; 
        return (T)xs.Deserialize(xsText); 
    } 
} 

问题

msdn says那:

When you convert from a double or float value to an integral type, the value is truncated. If the resulting integral value is outside the range of the destination value, the result depends on the overflow checking context. In a checked context, an OverflowException is thrown, while in an unchecked context, the result is an unspecified value of the destination type.

  • 为什么Client.ID的值变成 0当数据库中的值超过 int 允许的最大值时?
  • 是因为它是一个未经检查的上下文吗?如果是,我怎么知道?

我的代码在 C# 中,框架 4,在 VS2010 Pro 中构建。

请帮助,在此先感谢。

请您参考如下方法:

这里有些可疑的事情。 SetValue 不执行转换/转换(甚至不从 uint 到 int,刚刚测试过)。您最好在真正的 foreach 中放大 ForEach 代码并对其进行调试。

例如:

foreach (var o in rowEntity.GetType().GetProperties().Where(o => dt.Columns.OfType<DataColumn>() 
        .Select(p => p.ColumnName).Contains(o.Name))) 
{ 
    if (o.Name == "ID") 
    { 
        // Put a breakpoint here 
    } 
 
    o.SetValue(rowEntity, row[o.Name], null)); 
}