C# 从列表中筛选抽象类
我有一个C# 从列表中筛选抽象类,c#,C#,我有一个新列表(),其中包含一些不同的实现。由于特定的条件,我想过滤掉一些实现。如何做好这件事 1) if (condition1 && type is Implementation1) ... 2) if (condition2 && implementation.Name == "Implementation 1") ... 3) if (condition3 && implementation.Type == EnumType.Type1
新列表()
,其中包含一些不同的实现。由于特定的条件,我想过滤掉一些实现。如何做好这件事
1) if (condition1 && type is Implementation1) ...
2) if (condition2 && implementation.Name == "Implementation 1") ...
3) if (condition3 && implementation.Type == EnumType.Type1) ...
我认为1)不好,2)在编译时不工作3)可能好
对其他设计有什么建议吗
(由于禁令,无法在programmers.SE上发布)
编辑:
更多细节。想象一下抽象类(或接口):
以及在控制台上打印消息的classConsolePrinter: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>();
类基类{}
派生类:基{}
var listOfBase=新列表();
// ...
var enumerableOfDerived=listOfBase.OfType();
查看用于筛选的扩展方法的.OfType
class Base {}
class Derived : Base {}
var listOfBase = new List<Base>();
// ...
var enumerableOfDerived = listOfBase.OfType<Derived>();
类基类{}
派生类:基{}
var listOfBase=新列表();
// ...
var enumerableOfDerived=listOfBase.OfType();
如果类型在编译时已知,那么我会选择使用typeof(…)
操作符
如果类型在编译时未知,则必须通过Object.GetType()
检查系统.Type
,如果类型在编译时已知,则我会选择使用typeof(…)
操作符
如果在编译期间类型未知,那么您必须通过对象.GetType()
检查系统.Type
,您可以列出需要的原因吗?您可以列出需要的原因吗?