开发者

c# : Loading typed data from file without casting

开发者 https://www.devze.com 2023-02-12 18:13 出处:网络
Is there a way to avoid casting to a non-string type when reading data from a text file containing exclusivelyinteger values separated by integer markers (\'0000\' for example) ?

Is there a way to avoid casting to a non-string type when reading data from a text file containing exclusively integer values separated by integer markers ('0000' for example) ?

(Real-Life example : genetic DNA sequences, each DNA marker being a digit sequence.)

EDIT : Sample data : 581684531650000651651561156843000021484865321200001987984948978465156115684300002148486532120000198798400009489786515611568430000214848653212000019879849480006516515611684531650000651651561156843000021 etc...

Unless I use a binary writer and read byt开发者_运维技巧es, rather than text (because that is how data written at first),

I think this a funky idea, so "NO" would be the straight answer for this.

Just wanted to get a definitive confirmation to that here, just to be definitely sure.

I welcome any intermediate solution to write/read this kind of data efficiently without having to code a custom reader GUI to display it outside my app, intelligibly (in some generic reader/viewer).


The short answer is no, because a text file is a string of characters.

The long answer is sort of yes; if you put your data into a format like XML, a deserializer can implicitly cast the data back to the correct type (without you having to do it manually) based on your schema.


If you have control over the format, consider using a binary format for your file and use e.g. BinaryReader.ReadInt32.


rather then just casting, you really should use the .TryParse(...) method(s) of the types you are trying to read. This is a much more type-safe solution.

And to answer your question, other then using a binary file, there is not (to my knowledge) a way to do this without casting (or using the TryParse methods)


The only way to control all the read process is to read bytes. Else you read strings.

Edit : I Didn't talk about automatic serialization via XML because of the details on the file format you gave.


If the data is text and you need to access it as an integer, a conversion will be required. The only question is which code does the conversion.

Depending upon the file format, you could look for classes or libraries that already handle them. Otherwise, keep your code well organized so you don't have to pay attention to the conversion too much.

Some options:

// Could throw exceptions
var x = Convert.ToInt32(text);
var x = Int32.Parse(text);

// Won't throw an exception, just check the results
int x = 0;
if (Int32.TryParse(text, out x)) { ... }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号