[Unity&对象]怎么理解变量public 还是private ,还是使用getset方法定义

来源:互联网 发布:mac 双系统两个windows 编辑:程序博客网 时间:2024/05/31 19:33

怎么理解变量public 还是private ,还是使用getset方法定义


private 变量 只能被自己的 类 调用。


public 变量 可以被其他 类调用。



get set 方法的本质是,为了让 操作代码 的设计师 、程序员明白 这个变量 的使用 条件,和应用的 环境。便于工作 ,优化代码。

在参考资料1中 第30个技巧,提到 可以 使得 不同职能之间 的工作协调,使得 其他设计师 明白自己,能够改变什么变量。




get set 方法的几种使用方法

第1种用法,这种用法仅仅 是改变 了ID 的设置的类型

通常使用在 参考资料7 ,这种快速重构 继承 多接口 的时候。

public int ID

{get;

set;}


第2种用法,这种方法 为了使得 id 被封装(当且仅当id 为private 类型的时候),并且 其他函数可以通过 调用 ID,来改变id。

参考资料3 里面提到 封装性。

public(private) int id;

public int ID

{

get {return id;}

set {id = value;}

}



第3种用法,对 id 进行 条件限制,比如 用这种方法 设置分数, 0<分数<100,避免变量 超出范围,无效。

参考资料5,6 都显示,使用get;set 方法 ,可以对变量 设置IF 语句 进行 条件 的判断。

private int id;

public int ID

{

get {return id;}//get end

set {

if(value>0)

{

id = value;

}//if end

}//set end

}//public int ID end


第4种用法,这种用法 使得 id 这个变量 可以在其他 函数中被设置,get;set方法默认 是public ,可以设置为private ,一旦设置为private ,就只能在这个类中 得到该变量。

private int id;

public int ID

{

private get {return id;}//get end

set {

if(value>0)

{

id = value;

}//if end

}//set end

}//public int ID end




参考资料:

1.

unity使用Unity3D的50个技巧:Unity3D最佳实践

http://www.xlgps.com/article/430834.html

2.

c#中get,set属性的作用是什么?

https://zhidao.baidu.com/question/182739116.html?qbl=relate_question_2&word=unity%20get%20set%20%B7%BD%B7%A8%D3%D0%CA%B2%C3%B4%D3%C3

3.

java中什么是类的封装性

https://zhidao.baidu.com/question/1540144388047863747.html

4.

C#中的属性定义为public和定义为private再使用get()set()方法有区别吗

https://zhidao.baidu.com/question/116540361.html

5.

c#属性写法有几种形式,哪种更规范, 如果有别的写法请补充

https://zhidao.baidu.com/question/1178693760100976539

6.

c#中get,set属性的作用是什么?

https://zhidao.baidu.com/question/182739116.html?qbl=relate_question_2&word=unity%20get%20set%20%B7%BD%B7%A8%D3%D0%CA%B2%C3%B4%D3%C3

7.[Unity&接口]子类即继承接口类也继承MonoBehaviour的快速操作和重构实现

http://blog.csdn.net/bulademian/article/details/72884513

8.

9.

阅读全文
0 0