从Linq查询访问私有变量时感到困惑

时间:2014-04-14 00:25:34

标签: c# linq

我对为什么我可以从linq查询中访问私有变量感到困惑?

访问是在PropertyName方法中并访问_propertyName变量。我认为既然它是私人的,我就无法访问它?

public class ObjectGraph
{
    private readonly string _propertyName;

    public string PropertyName
    {
        get
        {
            // ermmm, not sure why this Select can access _propertyName???
            var parents = string.Join("/", Parents.Select(p => p._propertyName));
            return string.Format("{0}/{1}", parents, _propertyName);
        }
    }

    public ObjectReplicationContext Source { get; private set; }

    public int ClosestParentId { get; set; }

    public bool TraverseChildren { get; set; }

    public List<ObjectGraph> Parents { get; set; }

    public ObjectGraph(object source, string propertyName)
    {
        Source = new ObjectReplicationContext(source);
        _propertyName = propertyName;

        Parents = new List<ObjectGraph>();
        TraverseChildren = true;
    }
}

1 个答案:

答案 0 :(得分:2)

一个类总是可以访问自己的私有成员。 lambda只是一个存在于类中的匿名回调方法;它是由C#编译器提供的语法糖。

想象一下你有这个

private static string GetProperyName(ObjectGraph obj) {
  return obj._propertyName;
}

public string PropertyName
{
   get
   {
        // ermmm, not sure why this Select can access _propertyName???
        var parents = string.Join("/", Parents.Select(GetProperyName));
        return string.Format("{0}/{1}", parents, _propertyName);
    }
}

这相当于您的代码。