从c#到Objective-C的构造函数代码
本文关键字:构造函数 代码 Objective-C | 更新日期: 2023-09-27 18:10:55
我们必须将c#代码转换为Objective-C代码,我很难弄清楚如何创建一个没有参数的构造函数,而另一个有两个参数。这是我试图转换的c#代码:
namespace Account
{
class Program
{
public class Account
{
private double balance;
private int accountNumber;
public Account()
{
balance = 0;
accountNumber = 999;
}
public Account(int accNum, double bal)
{
balance = bal;
accountNumber = accNum;
}
}
}
}
这是我到目前为止对Objective C的了解不确定它是否正确
@interface classname : Account
{
@private double balance;
@private int accountNumber;
@public Account()
}
我愿意得到任何帮助,非常感谢你,Danny
您只需提供两个初始化式,它们采用一般形式:
@interface MONAccount : NSObject
@private
double balance;
int accountNumber;
}
/* declare default initializer */
- (id)init;
/* declare parameterized initializer */
- (id)initWithAccountNumber:(int)inAccountNumber balance:(int)inBalance;
@end
@implementation MONAccount
- (id)init
{
self = [super init];
/* objc object allocations are zeroed. the default may suffice. */
if (nil != self) {
balance = 0;
accountNumber = 999;
}
return self;
}
- (id)initWithAccountNumber:(int)inAccountNumber balance:(int)inBalance
{
self = [super init];
if (nil != self) {
balance = inBalance;
accountNumber = inAccountNumber;
}
return self;
}
@end
Objective C与其他语言有点不同。与其他语言相比,它的语法更奇怪。不过在我看来,你似乎对objective-c还没有多少了解。我建议你看看apple的文档或者找一本书来真正了解objective-c语法是如何工作的。学习语法应该不会花太长时间,但下面是你应该怎么做的。
<>之前
@interface NSObject : Account
{
@private
double balance;
int accountNumber;
}
-(void)account; //No Arguements
-(void)account:(int)accNum withBalance:(double)bal; //2 Arguements
@implementation Program
-(void)account
{
balance = 0;
accountNumber = 999;
}
-(void)account:(int)accNum withBalance:(double)bal
{
balance = bal;
accountNumber = accNum;
}