| Profilo di StevenDevelopmentalBlogElenchi | Guida |
|
20 agosto System.IConvertible - Its not a FerrariYou might be familiar with the System.Convert class, which has a number of methods for converting from/to different types. For example:
We live in a world of casting and you might find this code somewhat pointless. After all, it will still raise StackOverflowException and lose precision with floating poing conversions, so what's the point? The convert class is capable of converting an instance of ANY type into one of the common base types (sting, int, ulong, char, etc). If a type implements the System.IConvertible interface, it can define how conversions of that type will occur. Lets consider a (not so practical) example. Say we have a product class with the following properties:
Our Product class also has a parameterless constructor. In this example, we also make the Product class implement the IConvertible interface. This forces us to implement 16 methods and 1 property. Those methods all relate directly to conversion. For example, here's the implementation of one of those methods:
What we are saying here is that if someone tries to convert our Product instance to a ulong then it will simply assign the ProductId. Our test code looks like this:
The output is the number "7" because that is how our implementation of IConvertible tells the Convert class to handle conversions to UInt64. Simple eh?
CommentiPer aggiungere un commento, accedi con il tuo Windows Live ID (se utilizzi Hotmail, Messenger o Xbox LIVE possiedi già un Windows Live ID). Accedi Non hai ancora un Windows Live ID? Registrati RiferimentiL'URL di riferimento per questo intervento è: http://stevennagy.spaces.live.com/blog/cns!B2EFDBF0964586B3!248.trak Blog che fanno riferimento a questo intervento
|
|
|