public class Libro
{
public string Titolo { get; set; }
public string Autore { get; set; }
public string Editore { get; set; }
public int ISBN { get; set; }
public int Pagine { get; set; }
public decimal Prezzo { get; set; }
public int Quantità { get; set; }
不是所有型別的字串,我不知道如何將 int 和 decimal 值轉換為一個表格,在該表格中顯示我在 a 上的書籍串列(標題、作者、出版商和價格)檔案.txt
public Libro BuildLibro(string input)
{
Libro result = null;
if (!String.IsNullOrEmpty(input))
{
var inputArray = input.Split('*');
if (inputArray.Length >= 6)
{
result = new Libro();
result.Titolo = inputArray[0];
result.Autore = inputArray[1];
result.Editore = inputArray[2];
if (!string.IsNullOrEmpty(inputArray[3]))
{
int.TryParse(inputArray[3], out int num);
result.ISBN= num;
}
if (!string.IsNullOrEmpty(inputArray[4]))
{
int.TryParse(inputArray[4], out int num);
result.Pagine = num;
}
if (!string.IsNullOrEmpty(inputArray[5]))
{
decimal.TryParse(inputArray[5], out decimal num);
result.Prezzo = num/100;
}
if (!string.IsNullOrEmpty(inputArray[6]))
{
int.TryParse(inputArray[6], out int num);
result.Quantità = num;
}
}
}
return result;
}
}
}
uj5u.com熱心網友回復:
前言
自發布此答案以來,該問題已被大量編輯。我已建議應恢復編輯,因此此答案對于 2 月 14 日(修訂版 3)編輯之前發布的問題仍然有效,并且發布的新問題包含修訂版 3 的文本
修訂版 2 的原始建議
當你到達 ISBN 時,你改變了策略
ISBN = 4, Pagine = 5, Prezzo = 6, Quantità = 7
像這樣分配編輯名稱是有意義的:
Editore = content[3]
意思是“把content陣列的第四個元素,也就是一個字串陣列,放到editors屬性里面,就是一個字串”
我想你會嘗試過以下模式:
ISBN = content[4]
但這不會成功,因為contentis full of strings而 ISBN 是 an intand 即使一個字串純粹只充滿數字字符,這并不意味著它是一個 number。這將給出一些錯誤,例如“沒有隱式轉換......”
我猜你洗掉了內容,只留下了一個硬編碼的 4 分配為 ISBN,它將在語法上編譯,但在邏輯上是不正確的。4從字面上看,這將修復每個 ISBN
相反,您應該將字串決議為 int。這很容易,我們可以這樣做:
ISBN = int.Parse(content[4])
同樣對于小數有一個 decimal.Parse
這可能會暴露其他問題,例如,如果其中一個值包含一些非數字字符(例如包含連字符的 ISBN),但我們可以稍后解決...
uj5u.com熱心網友回復:
有很多方法可以從字串中決議資訊。
我建議使用正則運算式。例如,使用以下正則運算式,您可以決議由 * 分隔的三個字串:
(?'Title'[^*] )[*](?'Author'[^*] )[*](?'ISBN'[^*] )
使用正則運算式的優點是,在決議字串時檢查字串是否有效。要測驗正則運算式,我建議使用https://regex101.com之類的東西
在您的代碼中,您可以使用 C# 庫:
using System.Text.RegularExpressions;
Regex rx = new Regex(@"(?'Title'[^*] )[*](?'Author'[^*] )[*](?'ISBN'[^*] )",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Define a test string.
string text = "Harry Potter*Rowling*12345";
// Find matches.
MatchCollection matches = rx.Matches(text);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425439.html
標籤:C# asp.net-mvc
上一篇:動作過濾器.NET中的context.Result何時為空?
下一篇:遍歷非公開成員資料
