【发布时间】:2010-12-19 13:51:54
【问题描述】:
我有一些实现通用非泛型接口的泛型类。我创建了我的通用对象并将它们添加到列表中。我如何使用 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;
}
【问题讨论】:
标签: c# generics operators interface