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); } 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?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)
3 Réponses :
Créer un constructeur sur FOO qui accepte une valeur pour "nom": construisez maintenant votre foo comme ceci: p> var bar = new Foo("baz");
C'est correct. Vous pouvez facilement obtenir la méthode Setter privé à partir d'un PropertyInfo code> à l'aide de
getSetmethod (true) code>. Je suis à peu près sûr que c'est ce que Linq à SQL fait.
La requête est évaluée contre un magasin de données, qui n'a aucun concept de public ni de privé. Et même en code, il est possible d'accéder aux membres privés en utilisant une technique appelée réflexion. P>
Voici un extrait de code simple qui illustre un tel comportement: