如果我理解正确的话,我有一个带有指定int值的枚举列表。我需要保持前导0所以有没有办法将这个值视为字符串而不是int?
我的枚举
public enum CsvRowFormat
{
BeginningOfFile = 01,
School = 02,
Student = 03,
EndOfFile = 04
}
目前我正在读出这样的值,我发现效率低下
studentRowFormat.AppendFormat("0{0}",(int)TransactionFile.CsvRowFormat.Student).ToString();
答案 0 :(得分:3)
Int32有a ToString() that takes a format string。所以最简单的方法就是这样:
studentRowFormat.Append(((int)TransactionFile.CsvRowFormat.Student).ToString("D2"));
您不需要枚举声明中的前导0。
答案 1 :(得分:3)
您可以使用"{0:D2}"
作为格式字符串。它将使用前导零填充字符串,直到它的长度为2.
您正在使用的enum
只是存储您要分配的数值,而不是字符串值,因此它不会保留您提供前导零的事实的知识。原生enum
类型不能由字符串支持;它们必须由整数值支持。您可以创建自己的“看起来”类似于字符串支持的枚举的自定义类型,但使用这样的解决方案将比使用现有整数enum
的更合适的格式字符串更加努力。
答案 2 :(得分:0)
不幸的是,没有办法将值视为字符串而不是int。见C# Enum Reference。您可以使用其他答案提供的格式选项,或者您可以编写一个允许您的代码更清晰的结构。因为我不知道你使用枚举的原因,我觉得我必须指出结构有一些行为差异。以下是使用此解决方案的结构的示例:
public struct CsvRowFormat
{
public string Value { get; private set; }
private CsvRowFormat(string value) : this()
{
Value = value;
}
public static BeginningOfFile { get { return new CsvRowFormat("01"); } }
public static School { get { return new CsvRowFormat("02"); } }
public static Student { get { return new CsvRowFormat("03"); } }
public static EndOfFile { get { return new CsvRowFormat("04"); } }
}
样本用法:
studentRowFormat.Append(TransactionFile.CsvRowFormat.Student);
希望这有帮助!