简体   繁体   中英

Get property name in the property's Set{} method

In C# 4.0 I am doing the following:

public string PropertyA
{
  get;
  set
  {
    DoSomething("PropertyA");
  }
}

public string PropertyB
{
  get;
  set
  {
    DoSomething("PropertyB");
  }
}

..I have a lot of these properties and doing it manually will be a pain. Is there a way I could replace this with:

public string PropertyA
{
  get;
  set
  {
    DoSomething(GetNameOfProperty());
  }
}

..maybe using reflection?

In .NET 4.5 your DoSomething method should use the [CallerMemberName] parameter attribute:

void DoSomething([CallerMemberName] string memberName = "")
{
    // memberName will be PropertyB
}

Then just call it like this:

public string PropertyA
{
     get
     {
         ...
     }
     set
     {
         DoSomething();
     }
}

See MSDN on this.

There is no way to do this in current C# versions, reflection won't help. You could hack this with expressions and get compile time checking, but that's about it, you'd have to type even more code too

 DoSomething(()=>this.PropertyA); // have dosomething take an expression and parse that to find the member access expression, you'll get the name there

A good alternative if that's possible for you would be to use Postsharp to do this instead in a clean way, but that may not always be possible.

You can use reflection of GetCurrentMethod .

public string PropertyA
{
    get;
    set
    {
        DoSomething(MethodBase.GetCurrentMethod().Name.Substring(4));
    }
}

It's available for .Net 4.

As @hvd explains, the Name will return set_PropertyA , then use Substring to take the property name.

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