您可以使用枚举,在将它们添加到DataRow之前,只需要一些方法即可将它们转换为字符串。 例如,可以将转换器实现为扩展方法:
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
public class Product
{
public enum ProductionType
{
Unknown,
KanbanJit,
ZeroForty
}
private ProductionType type;
public ProductionType Type
{
get { return this.type; }
set { this.type = value; }
}
// ... other members of Product class ...
}
public static class ExtensionMethods
{
public static string ToString(this Product.ProductionType productionType)
{
switch (productionType)
{
case Product.ProductionType.KanbanJit: return "KANBAN/JIT";
case Product.ProductionType.ZeroForty: return "040";
default: return string.Empty;
}
}
}
public class Program
{
public static void Main()
{
// Create products, set their production type, and add them to a list
var products = new List<Product>();
products.Add(new Product() { Type = Product.ProductionType.KanbanJit });
products.Add(new Product() { Type = Product.ProductionType.ZeroForty });
// Convert the production types to string and add them to DataRow
foreach (var product in products)
AddProductionTypeToDataRow(product.Type.ToString());
}
static void AddProductionTypeToDataRow(string productionType)
{
// ... implementation comes here ...
Console.WriteLine(productionType);
}
}
==更新==
这是另一个没有扩展方法的类型安全解决方案:
using System;
using System.Collections.Generic;
public class Product
{
public sealed class ProductionType
{
private string name;
private ProductionType(string name = null) { this.name = name; }
public static implicit operator string(ProductionType type) { return type.name; }
public static readonly ProductionType KanbanJit = new ProductionType("KANBAN/JIT");
public static readonly ProductionType ZeroForty = new ProductionType("040");
// ... other constants ...
public static readonly ProductionType Unknown = new ProductionType();
}
private ProductionType type;
public ProductionType Type
{
get { return this.type; }
set { this.type = value; }
}
// ... other members of Product ...
}
public class Program
{
public static void Main()
{
// Create products, set their production type, and add them to a list
var products = new List<Product>();
products.Add(new Product() { Type = Product.ProductionType.KanbanJit });
products.Add(new Product() { Type = Product.ProductionType.ZeroForty });
// Convert the production types to string and add them to DataRow
foreach (var product in products)
AddProductionTypeToDataRow(product.Type);
}
static void AddProductionTypeToDataRow(string productionType)
{
// ... implementation comes here ...
Console.WriteLine(productionType);
}
}