Why does it work?

I searched the search queries, trying to find a way to call Control.DataBindings.Add , not using a string literal, but getting the property name from the property itself, which, I think, would be less error prone, at least for my particular case, since I usually let Visual Studio do the renaming when renaming the property. Thus, my code will look like DataBindings.Add(GetName(myInstance.myObject)... instead of DataBindings.Add("myObject"... So I found this:

  static string GetName<T>(T item) where T : class { var properties = typeof(T).GetProperties(); if (properties.Length != 1) throw new Exception("Length must be 1"); return properties[0].Name; } 

This will be called if I have a property called One , this way: string name = GetName(new { this.One }); that would give me "One" . "One" I do not know why this works and whether it is safe to use. I don’t even know what this new { this.One } means. And I do not know in what case it could happen that properties.Length not 1.

By the way, I just tested to rename my One property to Two , and Visual Studio turned new { this.One } into new { One = this.Two } , which when used with the GetName function gave me "One" , which does everything this is useless since the name that I am switching to Control.DataBindings.Add will still be β€œone” after the property is renamed.

+4
source share
2 answers

new { this.One } creates an instance of an anonymous type with one property, because you did not specify a name called "One". That is why it works.

if you use new { One = this.Two } , you give the property the name "One". If you leave the "One =" part, it will work again.

However, the method you use may be misunderstood if you do not know how it is intended to be used, and if you do not call it an anonymous type.

There is another way, if you do not want to use string literals, here is one example that you can find on the Internet:
http://www.codeproject.com/Tips/57234/Getting-Property-Name-using-LINQ.aspx

+6
source

No, you do not need to stick with string literals:

 public static class ControlBindingsCollectionExtensions { public static void Add<T>(this ControlBindingsCollection instance, Expression<Func<T, object>> property) { var body = property.Body as UnaryExpression; var member = body.Operand as MemberExpression; var name = member.Member.Name; instance.Add(name); } } 

Using:

 Control.DataBindings.Add<MyClass>(m => m.MyProperty); 
+3
source

Source: https://habr.com/ru/post/1335517/


All Articles