Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中的泛型列表中查找对象的索引#_C#_List_Object_Generics_Indexing - Fatal编程技术网

C# 在C中的泛型列表中查找对象的索引#

C# 在C中的泛型列表中查找对象的索引#,c#,list,object,generics,indexing,C#,List,Object,Generics,Indexing,我有一个通用类 public class foo <T> where T:boo { List<T> fooList; } 不幸的是,这不起作用,因为booObject无法转换为类型t 如何获取索引??? 提前感谢。您必须将参数booObject的类型更改为泛型类型T。这是因为您定义了类型T是派生形式boo,但它仍然不是boo。这意味着,它可能是从boo派生的某个类goo。但是,然后您会尝试从goo类型的对象列表中获取boo类型的对象的索引,这是没有意义的 此外,您

我有一个通用类

public class foo <T> where T:boo
{
  List<T> fooList;
}
不幸的是,这不起作用,因为booObject无法转换为类型t

如何获取索引???
提前感谢。

您必须将参数
booObject
的类型更改为泛型类型T。这是因为您定义了类型T是派生形式
boo
,但它仍然不是
boo
。这意味着,它可能是从
boo
派生的某个类
goo
。但是,然后您会尝试从
goo
类型的对象列表中获取
boo
类型的对象的索引,这是没有意义的

此外,您忘记了方法的返回类型,并实际返回了已计算的索引:

public class foo<T> where T : boo
{
    List<T> fooList;

    public int getIndex (T booObject)
    {
        int index = fooList.IndexOf (booObject);
        return index;
    }
}
公共类foo其中T:boo
{
列出愚人;
public int getIndex(boot对象)
{
int index=doulist.IndexOf(booObject);
收益指数;
}
}

有关泛型的更多信息,请查看。

booObject
的类型从
boo
更改为
T
public class foo<T> where T : boo
{
    List<T> fooList;

    public int getIndex (T booObject)
    {
        int index = fooList.IndexOf (booObject);
        return index;
    }
}