使用.Net中的私有集初始化属性

Mar*_*eal 5 c# linq reflection private

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);
}
Run Code Online (Sandbox Code Playgroud)

我刚刚使用私有修饰符因为它有效并且使我不会对我的代码感到愚蠢,但现在我需要创建一个新的Foo,我刚从我的属性中删除了私有修饰符.我真的很好奇,为什么ExecuteQuery成为一个有趣的IEnumerable工作?

编辑好了,所以私有修饰符不会反映看到setter,并且从答案中看来,ExecuteQuery(或者它是数据上下文?)使用反射来获取属性名称并忽略修饰符.有没有办法验证?我怎么能自己想出来?(在标签列表中添加反射)

Mat*_*ton 4

在 Foo 上创建一个接受“Name”值的构造函数:

public class Foo
{
    public Foo(string name)
    {
        Name = name;
    }

    public string Name { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

现在像这样构建你的 Foo :

var bar = new Foo("baz");
Run Code Online (Sandbox Code Playgroud)

编辑(阅读问题的其余部分)

我的猜测是 ExecuteQuery 使用反射来检查类并查找其属性。它可能并不关心 Name 上的 setter 是私有的 - 只是 Name 根本有一个 setter。