[英]What are the ways I can write this differently? - static bool M (int x) => x%2 == 0;
I'm currently studying for a test and I've looked up what Function, Action and Predicate mean and I know that only Action doesn't have a return value and Predicate returns a bool value which is what I need in my question.我目前正在学习测试,我已经查看了 Function、Action 和 Predicate 的意思,我知道只有 Action 没有返回值,而 Predicate 返回一个 bool 值,这是我在问题中需要的。 This is the code I got in the question:
这是我在问题中得到的代码:
static bool M (int x) => x%2 == 0;
These are the potential answers given:这些是给出的潜在答案:
A) Func <bool, int> A = M;
B) Func <int, bool> B = M;
C) Action <int, bool> C = M;
D) Predicate <int> D = M;
Based on what I've learned and some simple logic it should be B and D, right?根据我所学和一些简单的逻辑,它应该是 B 和 D,对吗? Can someone confirm this for me?
有人可以帮我确认一下吗?
Let's ask the compiler:让我们问编译器:
Clearly A) & C) are compiler errors.显然 A) & C) 是编译器错误。 So, B) & C) are correct.
所以,B) & C) 是正确的。
The Func<int, bool>
delegate for B) looks like this: B) 的
Func<int, bool>
委托如下所示:
public delegate TResult Func<in T, out TResult>(T arg);
And the Predicate<int>
delegate for D) looks like this: D) 的
Predicate<int>
委托如下所示:
public delegate bool Predicate<in T>(T obj);
Both match the signature for M
.两者都匹配
M
的签名。
You can call a static function by it's class. For example:您可以通过它的 class 来呼叫 static function。例如:
public class yourClass
{
> public static void DoSomething(bool isTrue)
> {
> //Here you can do some things
> }
}
yourClass.DoSomething(true);
if you want a function to return some value eg bool, string etc如果您想要 function 返回一些值,例如 bool、string 等
Public class yourClass
{
>public static bool DoSomething(bool isTrue)
>{
>>if(isTrue)
>>{
>>return false;
>>}
>>else
>>{
>>return true;
>>}
>}
}
bool isItTrue = yourClass.DoSomething(true);
A function that returns a value must always have a return value.返回值的 function 必须始终具有返回值。 If you remove the else-part from the example above, you will get an error that not all code returns a value.
如果您从上面的示例中删除 else 部分,您将得到一个错误,即并非所有代码都返回一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.