在函数中使用类成员 [英] Using class members in functions

查看:61
本文介绍了在函数中使用类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尚未将该变量作为参数发送给函数时,甚至从函数内部的类范围访问甚至设置(成员)变量,是否都是一种不好的做法?

Is it a bad practice to access and even set a (member) variable from the class scope inside a function, when this variable hasen''t been sent as an argument to the function ?

推荐答案

DiiJAY写道:

在函数内部


您是该课程的方法吗?
不,这不是一个坏习惯.
:)


Do you mean a method of the class?
No, it is not a bad practice.
:)


您的第二个样本
Your second sample
private void MyMethod(int MyVariable)
{
    MyVariable = 23;
}


没有任何意义,MyVariable是方法的输入参数,而不是类的变量成员.关于您要实现的目标,您的问题不是很清楚.如今,大多数人使用C#中的属性来获取和设置变量,但是没有理由不应该在类的方法中访问它们.


makes no sense, MyVariable is an input parameter to the method not a variable member of the class. Your question is not very clear as to what you are trying to achieve. Most people nowadays use properties in C# to get and set variables, but there is no reason why you should not access them within a method of the class.


我的意思是这样的...



{

私人int _variable

私有void MyMethod()
{
_variable = 23;
}

}


没有在MyMethod中将_variable作为参数,例如...

私有void MyMethod(int MyVariable)
{
MyVariable = 23;
}
I mean like this...


class
{

private int _variable

private void MyMethod()
{
_variable = 23;
}

}


whithout having _variable as an argument in MyMethod like...

private void MyMethod(int MyVariable)
{
MyVariable = 23;
}


这篇关于在函数中使用类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆