C# 如何找到指向接口的相同指针的元素?

C# 如何找到指向接口的相同指针的元素?,c#,C#,我有以下代码: interface Foo { } public class Bar : Foo { } public class Program { static public void Main() { var list = new List<Bar>() { new Bar(), new Bar(), new Bar() }; Foo foo = list[2]; // let foo contains 3'th elemen

我有以下代码:

interface Foo
{
}

public class Bar : Foo
{
}

public class Program
{
    static public void Main()
    {
        var list = new List<Bar>() { new Bar(), new Bar(), new Bar() };
        Foo foo = list[2]; // let foo contains 3'th element (it is not important)
        var index = list.IndexOf(foo);  //  What's the method with similar semantics?
        Console.WriteLine($"index = {index}");
        Console.ReadLine();
    }
}
接口Foo
{
}
公共类酒吧:富
{
}
公共课程
{
静态公共void Main()
{
var list=new list(){new Bar(),new Bar(),new Bar()};
Foo-Foo=list[2];//让Foo包含第3个元素(这并不重要)
var index=list.IndexOf(foo);//语义相似的方法是什么?
WriteLine($“index={index}”);
Console.ReadLine();
}
}

在c#?

中是否有此类功能的内置方法/实现要查找类型为
Foo
的所有元素,您可以使用:

var foos = list.OfType<Foo>().ToList();

你是说IndexOf所做的语言关键字吗?“语义相似的方法是什么?”这个问题对任何人都有意义吗?为什么需要另一种方法?也许我已经理解了:也许他想要找到实现Foo接口的所有对象。我总是喜欢在俱乐部玩。你是否意识到,即使你的代码被接受,它也会失败,因为列表中的所有实例都实现了
Foo
?@LmTinyToon:忘记C#中的指针,你说的是实例和引用。变量
foo
引用列表中的
Bar
实例,它是相同的引用。这就是为什么
IndexOf
(或下面我的
FindIndex
方法)即使没有有意义地覆盖
Equals
也能工作的原因。如果未重写,则只会比较两个对象是否为同一引用。
两者都创建新集合。
True
前一个偶数过滤器,因此如果您将在此列表中获得索引,它可能不是原始列表中项目的索引。
因此,我甚至提到了第二位(保留原始索引).
由于您只是对界面进行强制转换,您不需要使用类型,但强制转换
最初的问题是
我想检索列表中实现Foo接口的所有对象。是否有一种方法可以在c#中做到这一点?“
这意味着并非所有项都属于
Foo
类型。
var indices = list.Select((b, i) => new { Value = b, Index = i})
                  .Where(x => x.Value is Foo)
                  .Select(x => x.Index)
                  .ToArray();