在.Net中使用私有集初始化属性 [英] initializing properties with private sets in .Net

查看:107
本文介绍了在.Net中使用私有集初始化属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

I have just been using the private modifier because it works and kept me from being stupid with my code, but now that I need to create a new Foo, I've just removed the private modifier from my property. I'm just really curious, why does the ExecuteQuery into an IEnumerable of Foo's work?

编辑好吧,因此private修饰符不会使反射看不到设置者,并且从答案来看,似乎ExecuteQuery(或者它是数据上下文?)使用反射来获取属性.命名并忽略修饰符.有没有办法验证?我怎么能自己弄清楚呢? (将反射添加到标签列表中)

EDIT Ok, so the private modifier doesn't keep reflection from seeing the setter, and from the answers, it appears that ExecuteQuery (or is it the data context?) uses reflection to get property names and ignores the modifiers. Is there a way to verify that? How could I have figured that out on my own? (adding reflection to the tag list)

推荐答案

在Foo上创建一个接受名称"值的构造函数:

Create a constructor on Foo that accepts a value for "Name":

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

    public string Name { get; private set; }
}

现在像这样构造您的Foo:

Now construct your Foo like this:

var bar = new Foo("baz");

编辑(阅读其余的问题)

我的猜测是ExecuteQuery使用反射来检查类并找到其属性.也许不关心Name的设置者是私有的-只是Name完全有一个设置者.

My guess is that ExecuteQuery uses reflection to inspect the class and find its properties. It probably doesn't care that the setter on Name is private - only that Name has a setter at all.

这篇关于在.Net中使用私有集初始化属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆