实例化对象并调用方法,使用单行语法在 C# 或 C++ 中返回值?

Instantiate an object and call method returning a value in C# or C++ with single line of syntax?

本文关键字:C++ 返回值 语法 单行 调用 对象 方法 实例化      更新时间:2023-10-16

在花了一些时间用其他语言编码后,我刷新了 C# 和C++。 我想知道我是否可以做这样的事情:

class Customer
{
private long id;
public Customer()
{
id = 0;
}
public Customer(long initID)
{
id = initID;
}
public bool Add()
{
// TODO: Call web service to add a customer to the database
// ...
return true;
}
}

。电话

// Add Customer
// Two line way that is correct
Customer c = new Customer(1234);
bool isAdded = c.Add();
// One line way that isn't valid
bool isAdded = new Customer(1234).Add();

换句话说,我真的不需要客户对象...基本上用值实例化对象并运行该方法并返回该方法的结果并释放对象......所有这些都在一个语句中。

有没有办法在 C# 和/或C++的一行中做到这一点既干净又简单?

创建一个静态类(不过你想给它起更好的名字(

public static class CustomerOperations
{
public static bool Add(long initId)
{
// Do stuff using initId
return true;
}
}

然后这样称呼它:

var isAdded = CustomerOperations.Add(1234);