Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.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,我有一个泛型类,它为具体类型的谓词提供通用方法(我使用PredicateBuilder扩展方法) 因此,编译器不知道什么是TItem。让我感到困惑的是,泛型和()方法在没有明确指定类型参数的情况下工作基本上,泛型类型参数的类型推断是基于传递给该方法的参数工作的 所以和()。编译器推断TPred是PersonPredict,因为这是isadalt的类型,并且没有其他约束 对于Not()。这是它无法推断的——不是TItem 如果您真的希望这样做,那么可以使用两个类型参数声明GenericPredic

我有一个泛型类,它为具体类型的谓词提供通用方法(我使用
PredicateBuilder
扩展方法)


因此,编译器不知道什么是
TItem
。让我感到困惑的是,泛型
和()
方法在没有明确指定类型参数的情况下工作

基本上,泛型类型参数的类型推断是基于传递给该方法的参数工作的

所以
和()。编译器推断
TPred
PersonPredict
,因为这是
isadalt
的类型,并且没有其他约束

对于
Not()。这是它无法推断的——不是
TItem

如果您真的希望这样做,那么可以使用两个类型参数声明
GenericPredicate
,其中一个应该是子类本身

public class GenericPredicate<TPred, TItem>
    where TPred : GenericPredicate<TPred, TItem>, new()
公共类GenericPredicate
其中TPred:GenericPredicate,new()
以及:

公共类PersonPredicate:GenericPredicate

您可能希望将
GenericPredicate
作为
GenericPredicate
的子类,这样其他代码仍然可以只接受
GenericPredicate
。但是,在这一点上,它非常复杂-您最好只指定类型参数。

在两个示例中,编译器都尝试确定应该用于解析函数的谓词
TPred
的类型

在本例中:

isFemale.And(isAdult);
编译器看到名为
isAdult
PersonPredicate
已传递给函数。因此,它可以确定在函数调用中,
TPred
实际上是
PersonPredicate

在另一个例子中

isFemale.Not();
编译器没有提示来理解什么适合
TPred
。因此,它需要具体的指示来解决冲突

isFemale.Not<PersonPredicate>();
isFemale.Not();
现在,编译器可以正确解析调用



最后,您可能会认为,因为您正在将函数调用的结果分配给
PersonPredicate
,编译器应该已经选择了这个选项。不幸的是,函数目标分辨率不考虑指定值。这是因为当您使用
=
赋值时,还有其他因素在起作用。可能定义了隐式类型转换,运算符可能已重载,或者可能存在隐式构造函数。因此,无法保证受让人的类型与实际价值相同。

我想知道为什么我没有获得“你被绑架”徽章!?感谢Jon的子类解决方法。我会和我的团队讨论的谢谢,现在这有意义了。我在谷歌上搜索了这样一个简单明了的解释
public class PersonPredicate : GenericPredicate<PersonPredicate, Person>
isFemale.And(isAdult);
isFemale.Not();
isFemale.Not<PersonPredicate>();