Ste*_*eve 3 c# generics interface operators
我有一些实现通用非通用接口的通用类。我创建通用对象并将它们添加到列表中。我如何使用 LINQ 或任何其他方法来按泛型类型过滤列表。我不需要在运行时知道 T 。我向接口添加了一个类型属性,并使用 LINQ 通过它进行过滤,但我希望使用 is 运算符。这是我整理的一个简单的例子。
有任何想法吗?
interface IOperation
{
object GetValue();
}
class Add<T> : IOperation
{
public object GetValue()
{
return 0.0;
}
}
class Multiply<T> : IOperation
{
public object GetValue()
{
return 0.0;
}
}
private void Form1_Load(object sender, EventArgs e)
{
//create some generics referenced by interface
var operations = new List<IOperation>
{
new Add<int>(),
new Add<double>(),
new Multiply<int>()
};
//how do I use LINQ to find all intances off Add<T>
//without specifying T?
var adds =
from IOperation op in operations
where op is Add<> //this line does not compile
select op;
}
Run Code Online (Sandbox Code Playgroud)
您可以只比较底层非参数化类型名称:
var adds =
from IOperation op in operations
where op.GetType().Name == typeof(Add<>).Name
select op;
Run Code Online (Sandbox Code Playgroud)
请注意,在 C# 的下一版本中,由于差异,这将是可能的:
var adds =
from IOperation op in operations
where op is Add<object>
select op;
Run Code Online (Sandbox Code Playgroud)