I am writing a software which operates with different types of integers (uint, short, ushort, byte etc.). The problem is that types of these numbers are likely to change, or, in some cases different combination of these types will be needed. The question is: what are the best practices to handle this situation? I can think of using #define
or making classes generic. But there are no any suitable constrains for generic types.
EDIT: 开发者_开发技巧The integers are used in the configuration files for different hardware. They may use different endians or different types of integers.
With generics, the best constraint you can use here is :struct
, which isn't very restrictive and doesn't give you access to anything useful. If the problem is operators, then there are various hacks around that; MiscUtil provides operator support with generics, or dynamic
works too (almost as fast, as long as you aren't using Nullable<T>
).
A using
alias might help if you need compile time, i.e. (in each file)
using Number = System.Int32;
Value types cannot be abstracted using generics like this, there is no common base that gives you any useful functionality. You are best creating your own structs around the value types in .NET and coding them to have operators working with each other. Obviously what you do with these structures depends on what behaviour you choose to give them.
With these wrapping structures, you can also define a common base that gives you something useful.
精彩评论