你能用自动属性激活事件吗?

时间:2010-11-04 15:08:58

标签: c# events automatic-properties

我想知道我是否可以使用自动属性,并且仍然能够在属性更改时触发事件。这是我目前的课程。 (当然,实际的User类有更多的属性/字段。)

public delegate void UserEventHandler(object sender, EventArgs e);

public class User
{
    public event UserEventHandler Changed;

    private string _UserName;
    public string UserName
    {
        get
        {
            return _UserName;
        }
        private set
        {
            _UserName = value;
            this.OnChanged(EventArgs.Empty);
        }
    }

    protected void OnChanged(EventArgs e)
    {
        if (Changed != null)
        {
            Changed(this, e);
        }
    }
}

所以我想知道是否有一种方法可以利用自动属性并仍然可以触发OnChanged事件。 换句话说:半自动属性是否可能?

3 个答案:

答案 0 :(得分:5)

您可以使用PostSharp Example

答案 1 :(得分:0)

聚会很晚,但这个问题仍然出现在谷歌上。

有一个包与PostSharp示例的工作方式大致相同,但是是免费的:Fody.Propertychanged

项目的自述文件及其链接的维基页面,可以很好地解释它。

答案 2 :(得分:0)

我稍微修改了您的代码,以便可以访问事件并使用现成的EventHandler。

    // controller
   public function ReadFromPublic(){
      $path = public_path('clients.json');
      $data = json_decode(file_get_contents($path));
      $clients = $data->clients;

    return view('read', compact('clients'));
    }


  // view file
  @foreach($clients as $client)
   <div>
    {{$client->name}}
   </div>
  @endforeach

如何设置事件:

{
  "clients": [
    {
      "id": "59761c23b30d971669fb42ff",
      "isActive": true,
      "age": 36,
      "name": "Dunlap Hubbard",
      "gender": "male",
      "company": "CEDWARD",
      "email": "dunlaphubbard@cedward.com",
      "phone": "+1 (890) 543-2508",
      "address": "169 Rutledge Street, Konterra, Northern Mariana Islands, 8551"
    },
    {
      "id": "59761c233d8d0f92a6b0570d",
      "isActive": true,
      "age": 24,
      "name": "Kirsten Sellers",
      "gender": "female",
      "company": "EMERGENT",
      "email": "kirstensellers@emergent.com",
      "phone": "+1 (831) 564-2190",
      "address": "886 Gallatin Place, Fannett, Arkansas, 4656"
    },
    {
      "id": "59761c23fcb6254b1a06dad5",
      "isActive": true,
      "age": 30,
      "name": "Acosta Robbins",
      "gender": "male",
      "company": "ORGANICA",
      "email": "acostarobbins@organica.com",
      "phone": "+1 (882) 441-3367",
      "address": "697 Linden Boulevard, Sattley, Idaho, 1035"
    }
  ]
}

查看working demo