![](/img/trans.png)
[英]Converting a byte array to an array of primitive types with unknown type in C#
[英]Converting C# Data Types from unknown sources
將字符串(通常)轉換為適當的數據類型,同時還要實時進行驗證,似乎有很多困惑。 無論我在哪里-博客,文章,代碼示例,論壇..少數人似乎都有處理這些情況的首選方法。
這種情況通常是來自未知來源的字符串/對象,例如QueryString,Session / Viewstate,WebService等。
我看過很多不同的例子:
假設我們正在嘗試獲取id=
查詢字符串,並將其在我們的代碼中用作整數。 但是有人篡改了我們的網址並將其更改為
單程
int id = Convert.ToInt32(Request["id"]);
// "Input string was not in a correct format"
其他方式
int id = (int)Request["id"];
// "Input string was not in a correct format"
另一種方式
int id = int.Parse(Request["id"]);
// "Input string was not in a correct format"
我見過 (拋出異常並通知用戶這很有意義)
int id = 0;
try {
id = Convert.ToInt32(Request["id"]);
}
catch(Exception ex) {
lblError.Text = ex.Message;
}
if(id > 0) { ... }
最后,還有我個人使用的那個
int id = 0;
int.TryParse(Request["id"], out id);
// make sure it's not 0
if(id > 0) { // live a happy life }
這適用於所有其他類型, bool
, double
, decimal
等等。
請幫助我了解正確的方法,因為我發現自己每天都在使用此方法。
好吧,對於初學者,您應該使用:
int id;
if(!int.TryParse(Request["id"], out id)
//notify the user, or handle it someother way
而不是檢查id>0。如果解析成功,則int.TryParse(string, out int)
返回true
,否則返回false
。
System.ComponentModel
命名空間包含一個精心設計的框架,用於恰好執行這些類型的轉換。
為自己檢查名稱空間,但這將使您入門:
targetType newValue = (targetType) System.ComponentModel.TypeDescriptor.GetDescriptor(typeof(sourceType))
.ConvertTo((object)value, typeof(targetType))
您可以在一個與類型無關的集中式位置上免費獲得基本類型轉換,而不必搜索在原始類型上發現的不一致X.Parse或X.TryParse方法。
在基礎之上,您將獲得一個可擴展的框架,在其中可以編寫自己的類型轉換器。 ASP.NET MVC框架大量使用此命名空間來處理其類型轉換,例如將查詢字符串值轉換為方法參數。
我認為其中任何一個都不會真正被認為是“正確的”。 我喜歡使用Convert.ToInt32(),因為我可以獲得一些特定的異常,可以檢查它們是否有效。
正確:答案是,這取決於。 您應該了解類型轉換和解析之間的區別。 適當使用它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.