C#泛型:如何在泛型类中使用x.MaxValue / x.MinValue(int,float,double) [英] C# Generics : how to use x.MaxValue / x.MinValue (int, float, double) in a generic class

查看:209
本文介绍了C#泛型:如何在泛型类中使用x.MaxValue / x.MinValue(int,float,double)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WPF扩展工具包( http://wpftoolkit.codeplex.com/ )。

I'm using the WPF Extended Toolkit ( http://wpftoolkit.codeplex.com/ ).

它有一个我想使用的不错的NumericUpDown控件,但是在内部它使用double-意味着它使用double.MinValue和double.MaxValue。

It has a nice NumericUpDown control that I'd like to use, but internally it uses doubles - which means it uses double.MinValue and double.MaxValue.

我想使用相同的控件,但我需要一个通用版本-对于int而言,它需要使用int.MaxValue / MinValue,对于浮点数float.MaxValue / MinValue等。(我想您知道这个主意:))

I'd like to use the same control, but I need a generic version - for ints it needs to use int.MaxValue/MinValue, for floats float.MaxValue/MinValue, etc. (I think you get the idea :))

所以我虽然要将NumericUpDown复制到GNumericUpDown,其中T当然是Type ..
但这是行不通的,因为通用类型没有MinValue / MaxValue。
通常,我会使用'where'子句来指定基本类型,但这在afaik中不起作用,因为没有通用的接口定义'MinValue'和'MaxValue'。

So I though about copying the NumericUpDown to a GNumericUpDown, where T would ofcourse be the Type.. But this doesn't work, because a generic Type doesn't have MinValue / MaxValue. And normally I'd use the 'where' clause to specify a base-type, but this doesn't work as afaik there's no common interface that defines 'MinValue' and 'MaxValue'.

是否可以使用泛型解决此问题,或者我真的需要针对每种类型复制/粘贴/搜索并替换原始的NumericUpDown吗?

Is there a way to solve this with generics, or do I really need to copy/paste/search&replace the original NumericUpDown for each type ?

推荐答案

OP在另一个答案上发表了此评论:

The OP made this comment on another answer:


我想使用这些我的
XAML中的控件。我的想法是创建一个通用的
版本,然后创建像NumericUpDownInt这样的空类

GNumericUpDown {}那是
的路,还是有
更好/更清洁的方法

I want to use these controls in my XAML. My idea was to create a generic version, and then create empty classes like NumericUpDownInt : GNumericUpDown { } Would that be the way to go, or is there a better/cleaner way to your knowledge

如果您要走那条路线,只需直接通过最小值和最大值:

If you're going to go that route, then just pass the min and max directly:

class abstract GenericNumericUpDown<T>
{
    public GenericNumericUpDown(T min, T max) { ... }
}

class NumericUpDownInt : GenericNumericUpDown<int>
{
    public NumericUpDownInt() : base(int.MinValue, int.MaxValue) { ... }
}

class NumericUpDownFloat : GenericNumericUpDown<float>
{
    public NumericUpDownFloat() : base(float.MinValue, float.MaxValue) { ... }
}

class NumericUpDownDouble : GenericNumericUpDown<double>
{
    public NumericUpDownDouble() : base(double.MinValue, double.MaxValue) { ... }
}

这篇关于C#泛型:如何在泛型类中使用x.MaxValue / x.MinValue(int,float,double)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆