0

我一直在尝试设计一个用于某些插件的高效界面。我以为我找到了一个不错的接口,但尝试实现它并不顺利。所以我希望看看这里是否有人对如何做到这一点有更好的建议。它错误“不包含'GetEnumerator'的公共定义”

插件界面:

namespace ALeRT.PluginFramework
{
    public interface IQueryPlugin
    {
        string PluginCategory { get; }
        string Name { get; }
        string Version { get; }
        string Author { get; }
        System.Collections.Generic.List TypesAccepted { get; }
    }

    interface IQueryPluginRBool : IQueryPlugin
    {
        bool Result(string input, bool sensitive);
    }

    interface IQueryPluginRString : IQueryPlugin
    {
        string Result(string input, bool sensitive);
    }
}

本质上,我正在尝试获取应该使用的类型列表(类型可以是 URL、名称、电子邮件、IP 等)并将它们与查询插件中的值进行比较。每个查询插件都可能有多种它接受的类型。当它们匹配时,它会执行查询插件中的操作。

    [ImportMany]
    public IEnumerable<IQueryPlugin> QPlugins { get; set; }

    private void QueryPlugins(List<string> val, bool sensitive)
    {
        foreach (string tType in val) //Cycle through a List<string>
        {
            foreach (var qPlugins in this.QPlugins) //Cycle through all query plugins
            {
                foreach (string qType in qPlugins) //Cycle though a List<string> within the IQueryPlugin interface AcceptedTypes
                {
                    if (qType == tType) //Match the two List<strings>, one is the AcceptedTypes and the other is the one returned from ITypeQuery
                    {
                          //Do stuff here
                    }
                }
            }
        }
    }
4

2 回答 2

1

你的代码

foreach (string qType in qPlugins)
{
    if (qType = tType)
        {
            //Do stuff here
        }
}

不管用。你必须遍历qPlugins.TypeAccepted

于 2012-09-04T05:10:08.043 回答
1

首先。不要公开列表(如下面的行),因为它违反了得墨忒耳法则。这意味着插件无法控制它自己的列表。任何对该插件有参考的人都可以修改该列表。

System.Collections.Generic.List TypesAccepted { get; }

这个更好:

IEnumerable<TheType> TypesAccepted { get; }

但这仍然让任何人修改列表的元素(在插件不知情的情况下)。如果元素是不可变的,那很好。

更好的解决方案是在插件接口中创建方法。例如有一个访问者模式方法:

public interface IPluginTypeVisitor
{
    void Visit(AcceptedType type);
}

public interface IQueryPlugin
{
    string PluginCategory { get; }
    string Name { get; }
    string Version { get; }
    string Author { get; }
    void VisitTypes(IPluginTypeVisitor visitor);
}

但就您的循环示例而言,最佳解决方案很简单:

public interface IQueryPlugin
{
    string PluginCategory { get; }
    string Name { get; }
    string Version { get; }
    string Author { get; }
    bool IsTypeAcceptable(TheTypeType type); // get it, thetypetype? hahaha
}

private void QueryPlugins(List<string> val, bool sensitive)
{
    foreach (string tType in val) //Cycle through a List<string>
    {
        foreach (var plugin in this.QPlugins) //Cycle through all query plugins
        {
            if (plugin.IsTypeAcceptable(tType))
                //process it here
        }
    }
}
于 2012-09-04T05:29:53.397 回答