gpt4 book ai didi

c# - 对从 Linq 查询访问私有(private)变量感到困惑

转载 作者:行者123 更新时间:2023-11-30 16:59:53 26 4
gpt4 key购买 nike

我有点困惑为什么我可以从 linq 查询访问私有(private)变量?

访问是在 PropertyName 方法中访问 _propertyName 变量。我想因为它是私有(private)的,所以我无法访问它?

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;
}
}

最佳答案

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

这等同于您的代码。

关于c# - 对从 Linq 查询访问私有(private)变量感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23050116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com