使用带有接口到泛型的运算符

时间:2009-11-23 17:41:21

标签: c# generics operators interface

我有一些通用类实现了一个通用的非泛型接口。我创建我的通用对象并将它们添加到列表中。如何使用LINQ或任何其他方法来按通用类型过滤列表。我不需要在运行时知道T.我在接口中添加了一个type属性,并使用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;
    }

1 个答案:

答案 0 :(得分:4)

您只需比较基础的非参数化类型名称:

var adds =
    from IOperation op in operations
    where op.GetType().Name == typeof(Add<>).Name
    select op;

请注意,在下一版本的C#中,由于差异,这将是可能的:

var adds =
    from IOperation op in operations
    where op is Add<object>
    select op;