我正在构建一个计算器,我希望有一个名为ButtonDigit
的类型,它可能包含字符0
到9
,我想称之为{{1} char`,但这是不允许的,我不想要像:
ButtonDigit'. Ideally it would be derived from
我发现,当我希望存储字符时,必须始终实例化public class ButtonChar
{
public char Value { get; set; }
}
对象并访问ButtonChar
属性,这相当笨拙。理想的是char集Value
的一种别名,但我们没有得到它。我是否坚持使用0-9
对象或普通ButtonChar
,并始终在范围内检查它?
答案 0 :(得分:1)
使用generic class处理不同类型
public class Button<T>
{
public T {get;set;}
}
您可以在setter上添加通用验证系统 - 例如,通过保留将应用于任何输入的Func列表,例如:
var validations = new List<Func<T, bool>>();
if (validations.Any(validation => !validation(tValue))) {
throw new InvalidValueException(tValue);
}
// in the char example
validations.Add(myChar => myChar <= '9' && myChar >= '0');
答案 1 :(得分:0)
Char是一个结构,所以你不能继承它。我会说自定义ButtonChar类是一个不错的方法。
另一种方法是创建一堆char常量
public static class MyConstants
{
public static char Zero{get{return '0';}}
....
}
范围比较很容易,因为它是0-9
的连续范围