简体   繁体   中英

Need some explanation what is this C# weird syntax

I have seen following c# class:

public class Bucket: ObservableObject
{
   private ObjectId _oid;
   public ObjectId Oid
   {
      get { return _oid; }
      set
      {
         Set(() => Oid, ref _oid, value);
      }
   }
}

I understand _oid is a property of class Bucket. But I don't understand this:

Set(() => Oid, ref _oid, value);

How is it setting this property? Please explain me this syntax? What is it doing?

ObservableObject probably wants to notify clients of property changes, so when setting the internal field it also needs the name of the property; this is what () => Oid is for. The first parameter to set is probably an Expression<Func<TResult>> , which means the compiler does not generate code for the lambda, but rather builds a representation of the code as an abstract syntax tree (AST), which is passed to the Set method. This allows the Set method to inspect the AST and get the name of the property. If you use newer versions of C#, then Set also has an overload allowing you to pass the name of the property rather than the expression. I would use that as it has lower overhead: Set(nameof Oid, ref _oid, value);

The field is being set because you pass it by ref ( ref _oid ), so changes to the parameter inside Set will be reflected as changes to the field sent as a parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM