如何通过MEF共享类中的类型安全方法?

时间:2013-10-09 17:48:50

标签: c# mef

我有课我想通过MEF导出。在这个例子中它是字符串类型Displayer但在程序中将是许多特殊类型的显示器。我会做ImportMany< * IDisplayer>获取可用的显示器列表,我将从该列表中选择显示器,以显示给定的对象。

我的问题是如何才能使Display方法类型保存?或者投入它类型安全吗?并且还可以通过MEF使用显示器。

P.S。 使用MEF我不能像IDisplayer< * T>那样制作界面,因为我将无法获得ImportMany< * IDisplayer< * T>>什么的。

[DisplayableTypes(typeof(String))]
public class StringObjectDisplayer : IDisplayer
{
    public void Display(object objectToDisplay)
    {
        var displayableObject = (string)objectToDisplay;
    }

    private Type GetAttributeParamenters()
    {
        return GetType().GetCustomAttributes(typeof(DisplayableTypesAttribute), true).OfType<DisplayableTypesAttribute>().First().SupportedType;
    }
}

public class DisplayableTypesAttribute : ExportAttribute, IExportableElement
{
    public DisplayableTypesAttribute(Type supportedType)
        : base(typeof(IDisplayer))
    {
        SupportedType = supportedType;
    }

    public Type SupportedType { get; private set; }
}

public interface IDisplayer
{
    void Display(object objectToDisplay);
}

public interface IExportableElement
{
    Type SupportedType { get; }
}

0 个答案:

没有答案
相关问题