替代使用标记接口来测试派生的泛型类?

时间:2013-09-05 16:04:48

标签: c# generics interface marker-interfaces

我有一个应用程序,它使用来自公共基类的许多类型的派生类,并且一些派生类使用泛型。应用程序通常需要遍历派生类的集合,并识别特定类的类型以进行特殊处理。

问题是如何在不知道类型的情况下以简洁优雅的方式测试基类的特定泛型衍生物(因为它经常在项目中完成)?

'is'运算符不适用于此:

if (item is MyDerivedGenericClass<>)  // Won't compile

要解决此问题,我正在考虑使用空标记接口来识别集合中的特殊类。这似乎是最干净的解决方案。

几点说明:

  • 这是一个已关闭的项目,不会是商业分发的库。
  • 标记接口标记的类被标记为永久唯一类型,并且该类型的所有派生类都将正确继承标记。

以下示例:

public interface MarkerA { }  // Empty Interface
public interface MarkerB { }  // Empty Interface
public interface MarkerC { }  // Empty Interface

public class BaseClass { }

public class DerivedClassA : BaseClass { }
public class DerivedClassB : BaseClass { }
public class DerivedClassC : BaseClass { }

public class DerivedSpecialClass : BaseClass { }

public class DerivedSpecialA : DerivedSpecialClass { }
public class DerivedSpecialB : DerivedSpecialClass { }
public class DerivedSpecialC : DerivedSpecialClass { }

public class DerivedSpecialGenericA<T> : DerivedSpecialClass, MarkerA { }
public class DerivedSpecialGenericB<T> : DerivedSpecialClass, MarkerB { }
public class DerivedSpecialGenericC<T> : DerivedSpecialClass, MarkerC { }


public void ProcessClasses(List<BaseClass> list)
    {
        // Iterate through a list of mixed classes that all derive from BaseClass
        foreach (BaseClass item in list)
        {

            // Ideal approach, but doesn't compile:

            // Try to isolate select class types to do something interesting with
            if ((item is DerivedSpecialA) || (item is DerivedSpecialB) || (item is DerivedSpecialGenericB<>))
            {
                var specialItem = item as DerivedSpecialClass;

                DoSomethingInteresting(specialItem);

                Console.WriteLine(specialItem.Title);
            }


            // Alternative workaround that tests for the Marker instead

            // Try to isolate select class types to do something interesting with
            if ((item is DerivedSpecialA) || (item is DerivedSpecialB ) || (item is MarkerB))
            {
                var specialItem = item as DerivedSpecialClass;

                DoSomethingInteresting(specialItem);

                Console.WriteLine(specialItem.Title);
            }
        }
    }

有没有人对如何解决这个问题有更好的想法?

感谢。

3 个答案:

答案 0 :(得分:3)

当我需要编写根据对象类型而不同的代码,并且该代码作为虚拟方法不实用时,我使用实现为返回不可变信息的虚拟属性的标识符。这是更干净,并且不使用额外的实例存储,尽管通过类型参数初始化MarkerType会很好。

public class BaseClass 
{
    public abstract MarkerType { get; }  
}

public enum MarkerType { A, B, C }

答案 1 :(得分:0)

我一直在玩这个问题一段时间,而且我从一开始就认为代码结构很差。如果您在BaseClass内有基本级别的实现,则应使用IBaseClass通过策略模式实现。这样,一切都有一种标准化的解决方法。

在您的示例中,您有.Title作为specialItem的属性。我认为这对于所有MEF导出类都很常见。因此,这应该在IBaseClass内标准化。然后,您可以使用合同名称或通过向导出添加ExportMetaData属性并使用延迟加载来分离合同。

<强> IBaseClass:

/// <summary>
///     Provides mechanisms for working with BaseClasses.
/// </summary>
public interface IBaseClass
{
    /// <summary>
    ///     Gets the title of the MEF Exported class.
    /// </summary>
    /// <value>
    ///     The title.
    /// </value>
    string Title { get; }
}

<强> BaseClass的:

/// <summary>
///     Acts as a base implementation for all derived classes.
/// </summary>
public abstract class BaseClass : IBaseClass {

    /// <summary>
    ///     Initialises a new instance of the <see cref="BaseClass"/> class.
    /// </summary>
    /// <param name="title">The title.</param>
    protected BaseClass(string title)
    {
        // Set the title.
        Title = title;
    }

    #region Implementation of IBaseClass

    /// <summary>
    ///     Gets the title of the MEF Exported class.
    /// </summary>
    /// <value>
    ///     The title.
    /// </value>
    public string Title { get; private set; }

    #endregion
}

然后从那里派生你的课程......

Dervied Classes:

[Export("DerivedClasses", typeof(BaseClass))]
public class DerivedClassA : BaseClass 
{
    public DerivedClassA()
        : this("DerivedClassA")
    {
        /* IoC Friendly Constructor */
    }

    /// <summary>
    ///     Initialises a new instance of the <see cref="BaseClass"/> class.
    /// </summary>
    /// <param name="title">The title.</param>
    public DerivedClassA(string title) : base(title)
    {
        /* Construction Logic */
    }
}

请注意,我已在合同名称中添加了合同名称。您的特殊课程扩展了BaseClass的功能,并且该功能应该被分配到另一个界面。

<强> IDerivedSpecialBaseClass:

/// <summary>
///     Provides mechanisms for working with special BaseClasses.
/// </summary>
public interface IDerivedSpecialBaseClass : IBaseClass
{
    string SpecialProperty { get; }
}

此接口继承自IBaseClass,因为它源自同一个根。您的具体实现与上述相同,但实现IDerivedSpecialBaseClass而不仅仅是IBaseClass

<强> DerivedSpecialBaseClass:

/// <summary>
///     Acts as a base implementation for all derived special classes.
/// </summary>
public abstract class DerivedSpecialBaseClass : BaseClass 
{
    protected DerivedSpecialBaseClass()
        : this("DerivedSpecialBaseClass")
    {
        /* IoC Friendly Constructor */
    }

    /// <summary>
    ///     Initialises a new instance of the <see cref="BaseClass"/> class.
    /// </summary>
    /// <param name="title">The title.</param>
    protected DerivedSpecialBaseClass(string title) : base(title)
    {
        /* Constructor Logic */
    }

    #region Implementation of IDerivedSpecialBaseClass

    /// <summary>
    ///     Gets the special property.
    /// </summary>
    /// <value>
    ///     The special property.
    /// </value>
    public abstract string SpecialProperty { get; }

    #endregion
}

具体实施:

[Export("DerivedSpecialClasses", typeof(DerivedSpecialBaseClass))]
public class DerivedSpecialA : DerivedSpecialBaseClass
{
    /// <summary>
    ///     Initialises a new instance of the <see cref="DerivedSpecialA"/> class.
    /// </summary>
    public DerivedSpecialA()
        : this("DerivedSpecialA")
    {
        /* IoC Friendly Constructor */
    }

    /// <summary>
    ///     Initialises a new instance of the <see cref="DerivedSpecialA"/> class.
    /// </summary>
    /// <param name="title">The title.</param>
    public DerivedSpecialA(string title)
        : base(title)
    {
        /* Construction Logic */
    }

    #region Implementation of IDerivedSpecialBaseClass

    /// <summary>
    ///     Gets the special property.
    /// </summary>
    /// <value>
    ///     The special property.
    /// </value>
    public override string SpecialProperty
    {
        get { return @"Hello, from DerivedSpecialA"; }
    }

    #endregion
}

请注意使用的不同合同名称以及导出的不同类型。如果必须使用泛型,则可以以相同的方式添加第三个接口。

<强>接口

/// <summary>
///     Provides mechanisms for doing stuff with things.
/// </summary>
/// <typeparam name="T">The type of things to do stuff with.</typeparam>
public interface IDerivedSpecialBaseClass<T> : IDerivedSpecialBaseClass 
    where T : struct
{
    /// <summary>
    ///     Does stuff with things.
    /// </summary>
    /// <param name="thing">The thing.</param>
    void DoStuffWith(T thing);
}

<强>原始

/// <summary>
///     Acts as a base class for all generic special classes.
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class DerivedGenericBaseClass<T> : DerivedSpecialBaseClass, IDerivedSpecialBaseClass<T>
    where T : struct
{
    #region Implementation of IDerivedGenericBaseClass<T>

    /// <summary>
    ///     Does stuff with things.
    /// </summary>
    /// <param name="thing">The thing.</param>
    public abstract void DoStuffWith(T thing);

    #endregion
}

<强>混凝土:

[Export("DerivedSpecialGenericClasses", typeof(DerivedGenericBaseClass<>))]
public class DerivedSpecialGenericA<T> : DerivedGenericBaseClass<T>
    where T : struct
{
    #region Overrides of DerivedSpecialBaseClass

    /// <summary>
    ///     Does stuff and things.
    /// </summary>
    /// <param name="thing">The thing.</param>
    public override void DoStuffWith(T thing)
    {
        Console.WriteLine("Doing Stuff and Things with " + thing.GetType().Name);
    }

    /// <summary>
    ///     Gets the special property.
    /// </summary>
    /// <value>
    ///     The special property.
    /// </value>
    public override string SpecialProperty
    {
        get { return @"Hello, from DerivedSpecialGenericA"; }
    }

    #endregion
}

现在,在MEF中处理这些内容的最简单方法是创建一个Adapter类来处理组合。

适配器类

/// <summary>
///     Adapter class for MEF Imported contracts, deriving from BaseClass.
/// </summary>
public class Classes
{

    /// <summary>
    ///     Gets or sets the derived classes.
    /// </summary>
    /// <value>
    ///     The derived classes.
    /// </value>
    /// <remarks>
    ///     This list will be populated via MEF.
    /// </remarks>
    [ImportMany("DerivedClasses", typeof(BaseClass))]
    private IEnumerable<IBaseClass> DerivedClasses { get; set; }

    /// <summary>
    ///     Gets or sets the derived special classes.
    /// </summary>
    /// <value>
    ///     The derived special classes.
    /// </value>
    /// <remarks>
    ///     This list will be populated via MEF.
    /// </remarks>
    [ImportMany("DerivedSpecialClasses", typeof(DerivedSpecialBaseClass))]
    private IEnumerable<IDerivedSpecialBaseClass> DerivedSpecialClasses { get; set; }

    /// <summary>
    ///     Gets or sets the derived special generic classes.
    /// </summary>
    /// <value>
    ///     The derived special generic classes.
    /// </value>
    /// <remarks>
    ///     This list will be populated via MEF.
    /// </remarks>
    [ImportMany("DerivedSpecialGenericClasses", typeof(DerivedGenericBaseClass<>))]
    private IEnumerable<IDerivedSpecialBaseClass> DerivedSpecialGenericClasses { get; set; }

    /// <summary>
    ///     Initialises a new instance of the <see cref="Classes"/> class.
    /// </summary>
    public Classes()
    {
        // NOTE: This is a generic application catalogue, for demonstration purposes.
        //       It is likely you'd rather use a Directory or Assembly catalogue
        //       instead, to make the application more scalable, in line with the MEF
        //       ideology.
        var catalogue = new ApplicationCatalog();
        var container = new CompositionContainer(catalogue);
        container.ComposeParts(this);
    }

    /// <summary>
    ///     Processes the classes.
    /// </summary>
    public void ProcessClasses()
    {
        foreach (var item in DerivedClasses)
        {
            DoSomethingInteresting(item);
        }

        foreach (var item in DerivedSpecialClasses)
        {
            DoSomethingInteresting(item);
        }

        foreach (var item in DerivedSpecialGenericClasses)
        {
            DoSomethingInteresting(item);
        }
    }

    private void DoSomethingInteresting(IBaseClass specialItem)
    {
        Console.WriteLine("Something interesting has been done with: " + specialItem.Title);
    }
}

请注意,您不再需要检查哪个类型,因为它们已被拆分为三个单独的列表,使用MEF合同名称将它们过滤到正确的列表中。您不应该在适配器中引用具体实现,因为您在运行时不知道它们是否存在。如果他们不在,你的申请将会失败。

相反,我建议在ShouldProcess接口添加IBaseClass标志,并仅处理设置为true的那些。

foreach (var item in DerivedSpecialGenericClasses.Where(p => p.ShouldProcess == true))
{
    DoSomethingInteresting(item);
}

这些方面的东西。考虑分离您的顾虑。 MEF不知道流经它的是什么,所以你的应用程序也不会。让它成为焦点,让插件告诉您的应用程序他们需要什么。尽可能在最低级别实施这些检查,以便批量处理。

当您不完全了解程序流程,设计模式和可扩展架构时,使用MEF可能会很复杂。例如,这可以通过Lazy Loading实现,而处理检查则添加为ExportMetadata。它不会增加太多的开销,但如果你不能一次性完全吞咽你的插件,它可能会更复杂。当从其他不太可扩展的组合引擎移植到MEF时,通常需要从头开始重建您的插件结构;为了使它流畅,优雅。

答案 2 :(得分:0)

为什么不这样做:

item.GetType().GetGenericTypeDefinition().Equals(typeof(MyDerivedGenericClass<>))