访问静态方法中参数的私有成员?
这段代码如何编译?下面的代码在operator int 中可以访问类MyValue 的私有变量吗?为什么?
class Program
{
static void Main(string[] args)
{
Myvalue my = new Myvalue(100);
Console.WriteLine(my + 100);
Console.Read();
}
}
public class Myvalue
{
private int _myvalue;
public Myvalue(int value)
{
_myvalue = value;
}
public static implicit operator int(Myvalue v)
{
return v._myvalue;
}
}
How can this code compile? The code below in the operator int CAN access a private variable of the class MyValue? Why?
class Program
{
static void Main(string[] args)
{
Myvalue my = new Myvalue(100);
Console.WriteLine(my + 100);
Console.Read();
}
}
public class Myvalue
{
private int _myvalue;
public Myvalue(int value)
{
_myvalue = value;
}
public static implicit operator int(Myvalue v)
{
return v._myvalue;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为它在类中,所以可以访问其中的私有变量。就像您的实例公共方法一样。它也以相反的方式起作用。您可以从实例成员访问私有静态成员以创建 Monostate 模式。
Because it is in the class, it has access to private variables in it. Just like your instance public methods. It works the opposite way too. You can access private static members from instance members to create a Monostate pattern.
private
表示对于类来说是私有的,对于实例来说不是私有的。The
private
means private for the class and not private for the instance.operator int() 仍然是 MyValue 类的成员函数,因此可以访问 MyValue 类型的对象的所有字段。
请注意,静态仅意味着需要将 MyValue 对象作为参数传递给函数。
operator int() is still a member function of the MyValue class and so can access all fields of objects of type MyValue.
Note that the static just means that a MyValue object needs to be passed to the function as a parameter.