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

本文关键字:变量 Linq 查询 访问 对从 | 更新日期: 2023-09-27 17:58:13

我有点困惑,为什么我可以从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;
    }
}

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

类总是可以访问自己的私有成员。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);
    }
}

这相当于您的代码。