开发者

C# Custom data type! [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Int128 in .Net?

After I decided to implement my开发者_如何学JAVA Int128 in C#, I thought it would be nice to make it look like other dotNet data types.. But I could not implement the following feature:

  • suffix initialization: such as 13L and 0.2D

Can I make my own suffix in C#?

And if I can not.. how can I initialize it?

i.e

Int128 a= ??


No, you can't create your own form of literal in C#.

You could have an implicit conversion from int, long, uint and ulong, allowing:

Int128 a = 100;

but you wouldn't be able to specify values greater than ulong.MaxValue that way.

Having an implicit conversion from decimal would allow a larger range, but would be a bad idea because you would lose data for any value which wasn't just an integer.

Basically there's nothing which will allow a literal guaranteed-to-be-integer value greater than ulong.MaxValue - you could parse a string, but that's not really ideal. Alternatively you could create a constructor which took two ulongs, one for the bottom 64 bits and one for the top 64 bits.


You cannot create your own suffix initializers - this is part of the language and baked into the compiler. If you write your own C# compiler, on the other hand, you can do whatever you want and extend it in whichever way you wish.

As for how you would initialize it - it depends on how you wrote it. If it is a class, you would need to initialize it with the new keyword, or write some implicit conversions to numeric types that have less precision.

As Jon noted, you will have no way to actually set it to a value larger than ulong.MaxValue without some string manipulation. You will also have to represent in internally in some form (string? A number of ulongs?) and make sure all conversions and operations work correctly (what about overflows?).


No, you can't do suffix initialisation. That bit of cuteness will be available in the forthcoming C++ standard ... but I digress.

The most obvious choices are Int128(long hi, ulong lo) and Int128(string).


You could look at the new BigInteger struct in 4.0 for tips on initialization. http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜