1

我有一个用于实现“输出格式化程序”的接口,看起来有点像这样:

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; }
}

SoSomeFormattableEntity通过 Dapper 保存在数据库中,其OutputType属性存储为底层整数值(即,在INT列中)。你可以猜到,我想提供一个 a 的实例来根据它的属性IFormatOutput来处理 a 。SomeFormattableEntityOutputType

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

  1. 爷爷的可怕丑陋开关声明
  2. 将枚举值映射到类型的数组
  3. 基于反射的魔术映射枚举成员名称作为字符串到其他地方的类类型
  4. 一些涉及属性的映射机制

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

4

2 回答 2

0

怎么样:

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

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

于 2012-10-30T21:06:58.557 回答
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。

希望这是有道理的......

于 2012-10-30T22:18:44.317 回答