Q
数据类型在C#
1
A
回答
7
你可以使用几乎所有的整数类型(int
,uint
等);重要的部分是你如何格式它。在这种情况下:
string s = i.ToString("000");
的整数数据类型是只是价值 - 领先的零不存在或不存在 - 根本不是一个整数的工作。
你总是可以创建过程的自定义struct
,取整数值在constuctor(也许自定义转换运算符),覆盖ToString()
方法(可能Equals
,GetHashCode
等)。
只是踢:
public struct TriDigit : IComparable, IComparable<TriDigit>, IComparable<int>, IEquatable<TriDigit>, IEquatable<int>
{
private readonly int value;
public TriDigit(int value)
{
if (value < 0 || value > 999) throw new ArgumentOutOfRangeException("value");
this.value = value;
}
public override string ToString()
{
return value.ToString("000");
}
public override bool Equals(object obj)
{
if (obj == null) return false;
if (obj is TriDigit) return ((TriDigit)obj).value == value;
if (obj is int) return ((int)obj) == value;
return false;
}
public int CompareTo(object obj)
{
if (obj == null) return -1;
if(obj is TriDigit) return value.CompareTo(((TriDigit)obj).value);
if (obj is int) return value.CompareTo((int)obj);
return -1;
}
public override int GetHashCode()
{
return value;
}
public static explicit operator TriDigit(int value)
{
return new TriDigit(value);
}
public static implicit operator int(TriDigit value)
{
return value.value;
}
int IComparable<TriDigit>.CompareTo(TriDigit other)
{
return value.CompareTo(other.value);
}
int IComparable<int>.CompareTo(int other)
{
return value.CompareTo(other);
}
bool IEquatable<TriDigit>.Equals(TriDigit other)
{
return value == other.value;
}
bool IEquatable<int>.Equals(int other)
{
return value == other;
}
}
0
您可以简单地使用int
,或者如果它不能为负uint
(无符号整数)。数据类型较小,但对于大多数应用程序,它们不值得担心。
0
如果你说你需要一个整数,合法的范围从1到10,与从零开始的索引,那么答案是否定的。你需要为此制作自己的ADT。
2
听起来像是你想要的格式字符串,而不是数据类型。
Console.WriteLine("{0:D3}", i);
0
它是你想要的格式,而不是新的数据类型。在这里阅读所有内容:MSDN's page on Custom Numeric Format Strings。
0
您可以使用PadLeft(INT totalWidth,焦炭paddingChar)如..
int myNumber=12
string myStringNumber = myNumber.ToString().PadLeft(3, '0');
相关问题
- 1. C#,数据类型操作
- 2. NVarChar到C#数据类型
- 3. C++递归数据类型
- 4. 数据类型的OBJ-C
- 5. C中的数据类型
- 6. BSonElement to c#数据类型
- 7. C++双数据类型
- 8. C++通用数据类型
- 9. C#数据类型 - > Oracle数据
- 10. C#数据类型与MySql数据类型
- 11. 如何理解C++数据类型的本地数据类型?
- 12. 在C++中测试数据类型
- 13. 数据类型不匹配,在c#
- 14. 使用QueryRun数据类型在C#
- 15. 在C#复合数据类型
- 16. 在C#中查找数据类型#
- 17. 在C中存储数据类型
- 18. C#初始化整型数据类型
- 19. C#相当于C++/CLI数据类型
- 20. C++中等效数据类型的C#
- 21. C++类中的任意数据类型
- 22. C#数字数据类型命名
- 23. 代数数据类型相当于C
- 24. C#数学类型的数学类型?
- 25. 自定义数据类型C
- 26. C#处理多种数据库类型?
- 27. Android NDK,C++矢量数据类型
- 28. C++双数据类型问题
- 29. c# - 是SHORT数据类型还是INT?
- 30. C未知类型名称'数据'