gpt4 book ai didi

c# - 使用 is 运算符与泛型接口(interface)

转载 作者:行者123 更新时间:2023-11-30 21:23:26 24 4
gpt4 key购买 nike

我有一些实现通用非通用接口(interface)的通用类。我创建我的通用对象并将它们添加到列表中。我如何使用 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;
}

最佳答案

您可以只比较底层的非参数化类型名称:

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;

关于c# - 使用 is 运算符与泛型接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1784766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com