我声明了以下枚举:
public enum TransactionTypeCode { Shipment = 'S', Receipt = 'R' }
如何从TransactionTypeCode.Shipment获取值'S'或从TransactionTypeCode.Receipt获取'R'?
简单地做TransactionTypeCode.ToString()会给出一个Enum名称为"Shipment"或"Receipt"的字符串,因此它不会切断芥末.
您必须检查枚举的基础类型,然后转换为正确的类型:
public enum SuperTasks : int { Sleep = 5, Walk = 7, Run = 9 } private void btnTestEnumWithReflection_Click(object sender, EventArgs e) { SuperTasks task = SuperTasks.Walk; Type underlyingType = Enum.GetUnderlyingType(task.GetType()); object value = Convert.ChangeType(task, underlyingType); // x will be int }