【问题标题】:Test object implements interface from a dictionary测试对象从字典实现接口
【发布时间】:2012-09-23 22:29:13
【问题描述】:

我有一本注册类型的字典。

Dictionary<Type, Type> knownTypes = new Dictionary<Type, Type>() {
   { typeof(IAccountsPlugin), typeof(DbTypeA) },
   { typeof(IShortcodePlugin), typeof(DbTypeB) }
};

我需要测试一个对象是否将特定接口实现为键,如果是,则实例化对应的值。

public Plugin FindDbPlugin(object pluginOnDisk)
{
    Type found;
    Type current = type.GetType();

    // the below doesn't work - need a routine that matches against a graph of implemented interfaces
    knownTypes.TryGetValue(current, out found); /
    if (found != null)
    {
        return (Plugin)Activator.CreateInstance(found);
    }
}

将创建的所有类型(在本例中为 DbTypeA、DbTypeB 等)只会派生自类型 Plugin

传入的对象可能通过几代继承从我们尝试匹配的类型之一(即 IAccountsPlugin)继承。这就是为什么我不能pluginOnDisk.GetType()

有没有办法测试一个对象是否实现了一个类型,然后创建该类型的新实例,使用字典查找而不是暴力破解并在长循环中测试 typeof?

【问题讨论】:

    标签: c# system.reflection


    【解决方案1】:

    将此方法更改为泛型,并指定您要查找的对象的类型:

    public Plugin FindDbPlugin<TKey>(TKey pluginOnDisk)
    {
        Type found;
        if (knownTypes.TryGetValue(typeof(TKey), out found) && found != null)
        {
            Plugin value = Activator.CreateInstance(found) as Plugin;
            if (value == null)
            {
                throw new InvalidOperationException("Type is not a Plugin.");
            }
    
            return value;
        }
    
        return null;
    }
    

    示例:

    IAccountsPlugin plugin = ...
    Plugin locatedPlugin = FindDbPlugin(plugin);
    

    【讨论】:

    • also if(!(found is Plugin)){ throw new InvalidOperationException("does not implement Plugin"); }
    • TKey不在字典中时,你没有返回语句
    【解决方案2】:
    public Plugin FindDbPlugin(object pluginOnDisk) {        
        Type found = pluginOnDisk.GetType().GetInterfaces().FirstOrDefault(t => knownTypes.ContainsKey(t));
        if (found != null) {
            return (Plugin) Activator.CreateInstance(knownTypes[found]);
        }
        throw new InvalidOperationException("Type is not a Plugin.");
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-20
      • 1970-01-01
      • 1970-01-01
      • 2015-03-24
      • 2010-11-24
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      相关资源
      最近更新 更多