从列表中筛选抽象类
本文关键字:抽象类 筛选 列表 | 更新日期: 2023-09-27 18:28:53
我有一个new List<AbstractClass> ()
,它包含一些不同的实现。由于特定的条件,我想过滤掉一些实现。如何正确操作?
1) if (condition1 && type is Implementation1) ...
2) if (condition2 && implementation.Name == "Implementation 1") ...
3) if (condition3 && implementation.Type == EnumType.Type1) ...
我认为1)不好,2)在编译时不起作用,3)可能好吗?
对其他设计有什么建议吗?
(由于禁令,无法在程序员上发布。SE)
编辑:更多详细信息。想象一下抽象类(或接口):
class abstract MessagePrinter
{
void Print (string message);
}
以及在控制台上打印消息的类CCD_ 2。因此,当由于某些原因,我想停止在控制台上打印消息时,我需要从List<MessagePrinter>
中删除该实现。但是如果ConsolePrinter是用UpperCaseMessagePrinter
包装的呢?
class UpperCaseMessagePrinter : MessagePrinter
{
public UpperCaseMessagePrinter (MessagePrinter source) { /* ... */ };
void Print (string message)
{
source.Print (message.ToUpper());
}
}
所有的类型检查都是无用的。使用enum的解决方案#3有点帮助,但并不完美:/
查看用于筛选的.OfType
扩展方法。
class Base {}
class Derived : Base {}
var listOfBase = new List<Base>();
// ...
var enumerableOfDerived = listOfBase.OfType<Derived>();
如果在编译时已知类型,那么我会选择使用typeof(...)
运算符。
如果在编译期间类型未知,则必须通过Object.GetType()
检查System.Type
。