[英]Naming of parse string and assign value
Sometimes I have this kind of code, Any advise to improve the readability of result[0], result[1]...event the naming of result 有时我有这种代码,任何建议提高result [0],result [1] ... event的可读性的方法
var productData = "Egg 1.24 1.36";
var result = productData..Split(new char[] { ' ' });
var product = new
{
Name = result[0],
BuyPrice = result[1],
SellPrice = result[2],
};
I don't how you get productData but is it possible to maybe get it as a json? 我不怎么获得productData,但是有可能将其作为json来获得吗? That would improve the readability alot instead of splitting it and get string based on positions.
这将大大提高可读性,而不是将其拆分并根据位置获取字符串。
That's probably overkill, but you could use an extension method based on C# 7 and ValueTuple
to name your values right away. 这可能
ValueTuple
过分,但是您可以使用基于C#7和ValueTuple
的扩展方法ValueTuple
命名您的值。 For instance: 例如:
public static class StringExtensions
{
public static ValueTuple<string, string, string> Split(this string input, string delimiter)
{
var values = input.Split(new[] { delimiter }, StringSplitOptions.None);
return (values[0], values[1], values[2]);
}
}
Then use it like that: 然后像这样使用它:
var (name, buyPrice, sellPrice) = productData.Split(" ");
Console.WriteLine(name);
Edit: Actually, there's a smarter way. 编辑:其实,有一种更聪明的方法。 Just write an extension method to deconstruct an array:
只需编写扩展方法即可解构数组:
public static class ArrayExtensions
{
public static void Deconstruct<T>(this T[] values, out T item1, out T item2, out T item3)
{
item1 = values[0];
item2 = values[1];
item3 = values[2];
}
}
Now you can just use the original string.Split
and assign the values like the first example: 现在您可以使用原始
string.Split
并分配值,如第一个示例所示:
var (name, buyPrice, sellPrice) = productData.Split(new[] { " " }, StringSplitOptions.None);
Create Extension Method On The String Class Which Will Do The Split and Return an Object Of ProductData Class 在字符串类上创建扩展方法,该方法将进行拆分并返回ProductData类的对象
public static YourProductClass GetProductFromString(this string CompinedString)
{
// Do You Splitting Stuff Here and Assign The Values From String To NewProduct
return NewProduct;
}
Then In You Code 然后在你的代码
var ProductData = "Egg 1.24 1.36".GetProductFromString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.