2

Hi everyone I am not sure if what I want to do is even remotely possible but I am going to do my best to explain it and would really appreciate any suggestions / ideas,

Imagine I have :-

    public class Attribute{
        object Value;
        **(X1)**IComparer<T> comparer
    }
    public class AttributeValues
    {
        List<Attribute> values;
        SortedList<Attribute> Sort(){
            this uses the comparer defined in **(X1)** to sort the values in the list
        }
    }

These classes allow the user to create user defined attributes and select a pre-defined sort algorithm to sort the values In the simplistic case, I can do AttributesValues.Sort() using one of the comparers that I have created and compiled in source code which has been chosen by the user. This is fine when the comparison is known in advance such as a simple ascending alphabetical sort for example.

However, there are some circumstances where more logic is needed and it is not known in advance. For example, the string "4DFG5ET" might codify a date that needs to be sorted and there may be some other attribute with similar logic and so on.

If possible I don't want to keep writing the IComparer implementations and would love for it to be possible that somehow I could define the IComparer implementation in a text box or file at runtime and it would be somehow compiled in the program or persisted then available in the selction of comparisons that could be used to sort an attribute.

Does anyone have any suggestions on how to approach this?

Please ask if you would like me to clarify something as I know it is a slightly obscure question.

Many thanks in advance

Alex

4

4 回答 4

0

当然,有几种不同的技术支持这一点。Reflection.Emit 浮现在脑海中,由于 .NET 框架包含一个编译器,因此您还应该能够发出 C# 并将其即时编译为程序集,然后再加载。我相信在新的动态语言领域有更多的选择。

于 2012-06-12T20:24:26.217 回答
0

您可以使用CSharpCodeProvider(参见此处的文档)将提供的文本编译成 DLL,并使用反射加载生成的类。另外,这个SO question 可能对你有很好的帮助

于 2012-06-12T20:24:52.350 回答
0

我认为您可以为此使用MEF

引用:“托管可扩展性框架 (MEF) 是 .NET 的一个组合层,它提高了大型应用程序的灵活性、可维护性和可测试性。MEF 可用于第三方插件扩展性,或者它可以带来松散的好处 -将类似插件的架构耦合到常规应用程序。”

于 2012-06-12T20:25:16.917 回答
0

在我看来,你有两个选择。首先,您可以构建自己的语言来解析简单的用户命令,然后以 JIT 方式执行代码。

第二种选择实际上是让您的用户编写 C# 代码并即时编译它。(如前所述,Reflection.Emit 应该满足最简单的需求。)

编辑第三个选项并不完全是您想要的,但您可以为比较器插件设置一个目录。当您的应用程序启动时,它可以扫描该目录并加载程序集。使用反射,您可以提取任何实现 IComparer 接口的类,然后将它们作为列表提供给用户。(您还可以使用自定义属性来定义友好的用户名和描述等)。

在这种情况下,您不需要为了快速添加一些新的比较器而重新编译整个应用程序。此外,如果您有超级用户,他们可以使用一些免费的 .NET 代码编辑器来快速编写自己的比较器并将它们“安装”到目录中。

于 2012-06-12T20:27:15.997 回答