【发布时间】:2011-02-16 15:38:38
【问题描述】:
public class Foo
{
public string Name { get; private set;} // <-- Because set is private,
}
void Main()
{
var bar = new Foo {Name = "baz"}; // <-- This doesn't compile
/*The property or indexer 'UserQuery.Foo.Name' cannot be used
in this context because the set accessor is inaccessible*/
using (DataContext dc = new DataContext(Connection))
{
// yet the following line works. **How**?
IEnumerable<Foo> qux = dc.ExecuteQuery<Foo>(
"SELECT Name FROM Customer");
}
foreach (q in qux) Console.WriteLine(q);
}
我一直在使用 private 修饰符,因为它可以工作并且让我不会对我的代码变得愚蠢,但是现在我需要创建一个新的 Foo,我刚刚从我的属性中删除了 private 修饰符。我只是很好奇,为什么 ExecuteQuery 会变成 Foo 的 IEnumerable 的工作?
编辑好的,所以私有修饰符不会阻止反射看到设置器,从答案来看,ExecuteQuery(或者它是数据上下文?)似乎使用反射来获取属性命名并忽略修饰符。有没有办法验证?我怎么能自己想出来呢? (在标签列表中添加反射)
【问题讨论】:
标签: c# linq reflection private