Reputation: 61
I've come across this problem often, but I haven't found a satisfying solution yet.
I am implementing a reader for savegames (but it could also be applied to other types of files). Depending on the version, there are some added entries, but the order always remains the same. Therefore I created a class:
public class Entry<T> {
public T Value;
public readonly FileVersion MinVersion;
public Entry(T v = default(T), ScenarioVersion m = FileVersion.V115) {
Value = v;
MinVersion = m;
}
}
Now, you guess, I want to write those entries with as less code as possible. I want to write the line if (version >= MinVersion) { /* write data */ }
only once. The Entries can be primitive types or objects, which is the problem...
Should define an interface and implement it for every needed primitive type as a wrapper? Or is there a more elegant solution?
Upvotes: 2
Views: 1317
Reputation: 14386
(Looking at the comment for specific questions.)
Some values are only written if a certain condition is met.
Are these conditions known at the time the file is read/written or, when read, are they based on other data in the file? If the former (already known), pass in a Func<bool>
that must evaluate to true for the read or write operation to occur. The caller can supply an appropriate delegate or lambda method that makes the decision. You mention a minimum version in the question. I assume it is an example of this.
If the latter (values are read/written based on other data in the file), this is a wider question. If the decision can be made on data earlier in the file or in known places, load it and pass the appropriate arguments into the Func. Otherwise, you may need to look at more complex parsing mechanisms but I think this not what you are asking.
It is not a static structure and contains some things like struct { int len; char[len]; }.
.Net offers multiple ways to serialize objects but I suspect you want to read/write in a defined format, such as one that stores a string as a length followed by 8-bit characters. If the .Net mechanisms do not do what you want, you may have to write your own. See Byte for byte serialization of a struct in C# for more information on this, including the use of Marshal
to get the underlying bytes of a primitive.
Also, more for reference, if you want to avoid writing primitive types out, you could use public class Entry<T> where T: class
.
Upvotes: 1