[英]How does multiple method calls in an if-statement work?
我在 C# 中比较新。
我试图了解流动的代码是如何工作的。
public static int Method3()
{
//some code
If(Class1.Method1(int Variable1).Method2(Class3 Variable2))
{
//even more code
}
//some code
}
好的,现在有点上下文。
这个 if 语句在Method3中, Method3是 Class Class1 。
Method1采用 Int 值并返回 NULL 或 Class Class2 。
Method2采用 Class 让我们称之为Class3并返回true或false 。
因此,我理解要使 if 语句有效,条件必须返回true或false 。
根据我的理解,这将来自Method2 。
但是Method1在这里做什么呢? Method1 的output会发生什么? 对病情有影响吗?
我希望你们能明白我的意思。 如果没有请询问。
如果你得到一个名称更有意义的例子,就会更容易理解。
警告:此代码和您问题中的代码易受 NullReferenceException 的影响。 如果GetClient
返回null
,您将遇到异常。
例如:
public static bool SellingExample1()
{
int clientId = 21;
// Possible NullReferenceException
if(Shop.GetClient(clientId).OwesMoney())
{
// Send warning email to sales manager
}
// Do selling logic
}
public static bool SellingExample2()
{
int clientId = 21;
Client clientToSell = Shop.GetClient(clientId);
if (clientToSell == null) return false; // Check to avoid NullReferenceException before calling methods on a null object.
bool clientOwesMoney = clientToSell.OwesMoney();
if(clientOwesMoney)
{
// Send warning email to sales manager
}
// Do selling logic
}
public class Shop
{
public static Client GetClient(int clientId)
{
// Look the database and return the client
}
}
public class Client
{
public int Id { get; set; }
public string Name { get; set; }
public bool OwesMoney()
{
// Return true if there are unpaid bills
}
}
一种方法不需要 class。 它采用 class 的实例。
将 class 视为对事物的描述,将实例视为此类特定事物,例如 Cat 可能是 class ,其中“Tom the cat”可能是一个实例。
图片稍微复杂一些,因为方法可以是static
,这意味着它们是否属于 class,这意味着它们属于实例。 在下文中,我假设您正在处理 static 方法,因为您示例中的方法是 static。
因为您正在链接方法调用,所以我假设 Method1 返回一些可以调用 Method2 的内容(一个 object 实例)。
现在让我们看看如何根据这种理解修改您的代码:
public static int Method3()
{
//some code
int Variable1 = 42;
Class3 Variable2 = new Class3();
if(Class1.Method1(Variable1).Method2(Variable2))
{
//even more code
}
//some code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.