2012-10-30 64 views
1

我有一种实现“输出格式”,看起来有点像这样的接口类型的实例:C#:创建基于积分枚举值

public interface IFormatOutput {} 
public class HtmlOutputFormatter : IFormatOutput {} 
public class TextOutputFormatter : IFormatOutput {} 
// etc, etc... 

public enum OutputFormat { 
    Html, 
    Text, 
    HappyMeal, 
    Excel 
} 

public class SomeFormattableEntity { 
    int Id { get; set; } 
    OutputFormat OutputType { get; set; } 
} 

所以SomeFormattableEntity在数据库中通过小巧玲珑的坚持并将其OutputType属性存储为基础整数值(即,在INT列中)。您可以猜到,我想提供一个IFormatOutput的实例,以根据OutputType属性处理SomeFormattableEntity

有没有一些干净的最佳实践方式来处理这种类型的关系?我的想法到目前为止,包括与内脏工厂可能包括:

  1. 爷爷的可怕丑陋的switch语句
  2. 数组枚举值映射到类型
  3. 基于反射
  4. 魔术映射枚举成员名称作为字符串类类型别处
  5. 涉及一些映射机制属性

我意识到这是不可取的,要求的东西,它的类型是基于价值的实例,但它本身当涉及SQL时,很难避免这种情况。基本上问题是,所有具有不同.NET类型的多个“事物”都存储在一个表中。我一直在使用这个成语,并且无法找到一个优雅的解决方案。

回答

0

我可能会去使用FormatsOutputFor属性的自定义属性。然后用该属性修饰所有的IFormatOutput的实现。例如

[YourAttribute(OutputFormat.Html)] 
public class HtmlOutputFormatter : IFormatOutput {} 

然后在您的工厂:

// get all your formatters 
var formatters = AppDomain.CurrentDomain.GetAssemblies() 
    .SelectMany(s => s.GetTypes()) 
    .Where(p => Attribute.IsDefined(p, typeof(YourAttribute))); 

// Now go through each formatter and use the attribute to figure out which 
// output format it's for. Add these to some static IDictionary<OutputFormat, Type> 

你可能想建立一个映射OutputFormat值到Type一些内部缓存。然后你的工厂可以仔细检查你是否只有一种类型映射到每种输出格式,并且如果你试图获得一个没有相应类的枚举值的格式化程序,那么你不会从激活器中得到一些模糊的TypeLoadException。

希望这是有道理的...

0

如何:

OutputFormat format = OutputFormat.Excel; 
object obj = Activator.CreateInstance("myAssemblyName", format.ToString()); 

假设你的枚举有你的类型的确切名称的元素?