开发者

Accessing private member of a parameter within a Static method?

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
{
 开发者_如何学C   private int _myvalue;

    public Myvalue(int value)
    {
        _myvalue = value;
    }

    public static implicit operator int(Myvalue v)
    {
        return v._myvalue;
    }
}


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.


The private means private for the class and not private for the instance.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜