代码从C#到Objective-C的构造函数

时间:2011-10-08 05:55:43

标签: c# objective-c constructor

我们必须将我们的C#代码转换为Objective-C代码,我很难弄清楚如何创建一个没有参数的构造函数,而另一个构造函数有2个参数。 这是我想要转换的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;
        }
        }
}

}

这就是我目前为目标C所做的事情,不确定它是否正确

     @interface classname : Account 
   {
@private double balance;
@private int accountNumber;

@public Account()
   }

向任何帮助开放我非常感谢Danny

2 个答案:

答案 0 :(得分:3)

你只需提供两个初始化器,它采用一般形式:

@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

答案 1 :(得分:0)

目标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;

}