开发者

Generic only allowing only integers as type argument

开发者 https://www.devze.com 2023-01-24 09:25 出处:网络
I am writing a RationalNumber class in C# and would like to make it generic, but only allowing integers (int, byte, UInt32, my own BigInt class ...) as inputs - it doesn\'t make sense to have a ration

I am writing a RationalNumber class in C# and would like to make it generic, but only allowing integers (int, byte, UInt32, my own BigInt class ...) as inputs - it doesn't make sense to have a rational number based on floats or even regular objects like Control.

However, it doesn't seem that I can filter out non-integer 开发者_如何学Pythontypes when declaring the class.

Did I overlook something?


No you can't.

And you have the additional problem that there is no arithmetic constraint either. So there is no statically typed way to use the operators of your type argument either. So you'll need to use dynamic which is slower (unless they improved the runtime/jitter since .net 3.5).

Some projects with similar problems didn't make the class generic at all, and used a code generator to specialize it instead.

0

精彩评论

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