Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.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#_Generics - Fatal编程技术网

C# 基类中的泛型可以在父类中指定吗

C# 基类中的泛型可以在父类中指定吗,c#,generics,C#,Generics,我有一个基类,它的方法在C中使用泛型类型,然后我有其他从这些类继承的类,我想在父类中指定类型,以避免到处都有尖括号 下面是我的基类CBaseHome中的一个示例方法 public List fetchAllCBaseDb db,bool includeEmpty=true,其中T:CBaseTable,new { List retVal=新列表; ... 返回返回; } 我有一个从这个类继承的父类,而不重写这个函数 在随后使用这个的类中,我有以下代码 List<student> st

我有一个基类,它的方法在C中使用泛型类型,然后我有其他从这些类继承的类,我想在父类中指定类型,以避免到处都有尖括号

下面是我的基类CBaseHome中的一个示例方法

public List fetchAllCBaseDb db,bool includeEmpty=true,其中T:CBaseTable,new { List retVal=新列表; ... 返回返回; } 我有一个从这个类继承的父类,而不重写这个函数

在随后使用这个的类中,我有以下代码

List<student> students = new limxpoDB.Home.student().fetchAll<student>(db, false);
所以这里的Home.student类继承了CBaseHome类,而student继承了CBaseTable

我希望能够在Home.student类中说,该类的唯一有效泛型类型是student,因此我的消费代码看起来像

List<student> students = new limxpoDB.Home.student().fetchAll(db, false);
我在这里意识到差别很小,但我也在一些VB>Net代码中使用了这个库,它看起来很糟糕

有什么想法吗


感谢

子类无法强制方法上的泛型类型参数。因此,如果我有:

public class Parent {
    public List<T> GetStuff<T>() { ... }
}
我不能:

public class Child : Parent {
    // This is not legal, and there is no legal equivalent.
    public List<ChildStuff> GetStuff<ChildStuff>() { ... }
}
您可以做的是使父类泛型,而不是它的方法:

public class Parent<T> {
    public List<T> GetStuff() { ... }
}

public class Child : Parent<ChildStuff> {
    // GetStuff for Child now automatically returns List<ChildStuff>
}

子类不能强制方法上的泛型类型参数。因此,如果我有:

public class Parent {
    public List<T> GetStuff<T>() { ... }
}
我不能:

public class Child : Parent {
    // This is not legal, and there is no legal equivalent.
    public List<ChildStuff> GetStuff<ChildStuff>() { ... }
}
您可以做的是使父类泛型,而不是它的方法:

public class Parent<T> {
    public List<T> GetStuff() { ... }
}

public class Child : Parent<ChildStuff> {
    // GetStuff for Child now automatically returns List<ChildStuff>
}

.Net公共成员名称应为大写。Home.student是否确实从CBaseHome继承?您能告诉我们声明Home.student类的行吗?var students=new limxpodb.Home.student.fetchAlldb,false;?手头没有编译器,但您可以试试这个。@Chris Home.student继承自CBaseHome,下面是一行代码“public class student:CBaseHome”@Wiktor Zychia-使用此代码时,编译器会抱怨无法从用法推断类型,并要求显式定义类型参数。Net公共成员名称应为大写。Home.student是否真的从CBaseHome继承?您能告诉我们声明Home.student类的行吗?var students=new limxpodb.Home.student.fetchAlldb,false;?手头没有编译器,但您可以试试。@Chris Home.student继承自CBaseHome,下面是代码行“public class student:CBaseHome”@Wiktor Zychia-使用此代码时,编译器会抱怨无法从用法推断类型,并要求显式定义类型参数。非常感谢。我将where T:CBaseHome移到类中,而不是将其排序的方法。太好了,谢谢。我将where T:CBaseHome移到类中,而不是将其排序的方法。谢谢