一个类怎样调用另一个类中的属性和方法

一个类怎样调用另一个类中的属性和方法,第1张

如果两个类都在同一个包里面,或者已经在题头的时候有import导入
当目标类提供了相应的public方法可以调用的时候,就可以被调用。或者是new一个对象,调用对象的方法的方式来调用

tableView:didSelectRowAtIndexPath: 是一种委托方法。你不应该直接调用它。它被要求你选定的表视图行时。
应创建一个委托时为 LeftController,所以 LeftController 可以保持该委托其自己的连接。
在LeftControllerh中的实现:
@class LeftController;
@protocol LeftControllerDelegate
-(void)leftController:(LeftController )leftController didSelectTableView:(UITableView )tableView rowAtIndexPath:(NSIndexPath )indexPath;
@end
@interface LeftController : UIViewController
@property(nonatomic, weak) id<LeftControllerDelegate> delegate;
// other public properties
-(id)initWithDelegate:(id<LeftControllerDelegate>)delegate;
// other public methods
@end
在LeftControllerm中的实现:
-(id)initWithDelegate:(id<LeftControllerDelegate>)delegate
{
self = [super init];
if (self) {
selfdelegate = delegate;
}
return self;
}
-(void)viewDidLoad
{
[super viewDidLoad];
//create the tableView
//set the tableView delegate
tableViewdelegate = self;
//do other view setup
}
-(void)tableView:(UITableView )tableView didSelectRowAtIndexPath:(NSIndexPath )indexPath
{
[selfdelegate leftController:self didSelectTableView:tableView rowAtIndexPath:indexPath];
}
在其他视图控制器实现中,例如MyOtherControllerm:
//create instance of LeftController that has self as delegate
LeftController left = [[LeftController alloc] initWithDelegate:self];
与实现委托方法:
-(void)leftController:(LeftController )leftController didSelectTableView:(UITableView )tableView rowAtIndexPath:(NSIndexPath )indexPath
{
//Yay! This instance of MyOtherController has received the delegate message from LeftController, including details of table view and row selected
}
有效地在这里,你有委派连接消息到 LeftController,并反过来你授权的 LeftController 功能给其委托。当您创建并初始化它的 init 方法中设置其委托。

假设你想在类a里调用类b的函数int
f(x),两种办法:
1、class
a::b
也就是说将b定义为a的父类,
这样你就可以自然的在a里面用f(x)了
2、class
a
{
b
b_ins;
int
g(x);
}
int
g(x)
{
return
b_insf(x)
}
也就是说你可以在a里面使用一个b的对象作为成员变量,这样就可以用他的函数了

public class class_1 {
public final static String nema="杨国政";
}
在其他类中调用的方式是 public static void main(String[] args) {

String name = class_1nema;

}

C#是一个面向对象的编程语言。这种编程模式关注的是对象的行为和属性。比如猫抓老鼠这个例子中:猫和老鼠都是对象,用两个类表示:猫类Cat,老鼠类Mouse。猫表现出了两种行为:听(老鼠的叫声)Listen(Mouse)和抓(老鼠)Catch(Mouse);至少一种属性:行动速度Speed。老鼠表现出了一种行为:叫Chitter;至少一种属性:叫声的大小Loudness。这样的话可以如下定义两个类:using
System;class
Cat
{
public
void
Listen(Mouse
m)
{
ConsoleWriteLine("cat
listening"); }
public
void
Catch(Mouse
m)
{
ConsoleWriteLine("cat
catching");
}
public
float
Speed
{
get;
set;
}}class Mouse
{
public
void
Chitter()
{
ConsoleWriteLine("mouse
chittering"); } public
float
Loudness
{
get;
set;
}} 实现猫抓老鼠的过程,就是实例化上述两个类,并调用相关方法。编码如下:using
System;class
Program
{
public
static
void
Main()
{
Cat
c
=
new
Cat(); Mouse
m
=
new
Mouse();
ConsoleWriteLine("begin");
mChitter();
cListen(m);
cCatch(m);
ConsoleWriteLine("over");
}}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/13302482.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2025-08-31
下一篇2025-08-31

发表评论

登录后才能评论

评论列表(0条)

    保存