编辑
2025-09-25
C#
00

目录

摘要
正文
特性
AlsoNotifyForAttribute(允许注入指向不同属性的通知)
DoNotNotifyAttribute(不通知)
一个例子

摘要

Fody是一个用于C#项目的代码增强工具。它通过IL(Intermediate Language)重写技术,允许您在编译期间修改程序集的IL代码,以实现各种功能,如属性更改通知、自动实现接口、自动属性注入等。Fody使用插件方式工作,每个插件都可以用于特定的需求。

正文

要使用Fody,首先需要在您的C#项目中安装Fody NuGet包。在Visual Studio中,可以通过NuGet包管理器来执行此操作。打开项目,然后执行以下步骤:

  1. 在“解决方案资源管理器”中,右键单击项目,选择“管理NuGet程序包”。
  2. 在NuGet包管理器中,搜索并安装Fody包。
  3. 安装PropertyChanged.Fody包

image.png

新建一个Person类

C#
public class Person: INotifyPropertyChanged { public string Name { get; set; } public int Age { get; set; } public event PropertyChangedEventHandler? PropertyChanged; }

image.png

C#
public partial class Form1 : Form { Person person = new Person(); public Form1() { InitializeComponent(); person.PropertyChanged += Person_PropertyChanged; } private void btnProperty_Click(object sender, EventArgs e) { person.Name = "Test"; person.Age = 100; } private void Person_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) { switch (e.PropertyName) { case "Name": MessageBox.Show((sender as Person).Name); break; case "Age": MessageBox.Show((sender as Person).Age.ToString()); break; default: break; } } }

特性

我们需要针对某些特殊需求进行调整,比如更新A属性同时保留B属性,或者需要禁止通知某些属性等等。在这种情况下,Fody提供了特殊的标记属性功能,让我们能够轻松实现这些需求。

AlsoNotifyForAttribute(允许注入指向不同属性的通知)

C#
public class Person: INotifyPropertyChanged { [AlsoNotifyFor("Name")] public string FirstName { get; set; } //当FirstName或LastName改变时,通知Name [AlsoNotifyFor("Name")] public string LastName { get; set; } public string Name { get; set; } public int Age { get; set; } public event PropertyChangedEventHandler? PropertyChanged; }

DoNotNotifyAttribute(不通知)

C#
public class Person: INotifyPropertyChanged { [AlsoNotifyFor("Name")] public string FirstName { get; set; } //当FirstName或LastName改变时,通知Name [AlsoNotifyFor("Name")] public string LastName { get; set; } public string Name { get; set; } public int Age { get; set; } [DoNotNotify] public string Department { get; set; } //不通知 public event PropertyChangedEventHandler? PropertyChanged; }

一个例子

C#
public partial class Form1 : Form { Person person = new Person(); public Form1() { InitializeComponent(); BindData(); } private void btnProperty_Click(object sender, EventArgs e) { person.Name = "张三"; person.Age = 123; } //绑定属性 private void BindData() { txtName.DataBindings.Add("Text", person, "Name", false, DataSourceUpdateMode.OnPropertyChanged); txtAge.DataBindings.Add("Text", person, "Age", false, DataSourceUpdateMode.OnPropertyChanged); } }

image.png

再修改一下Person类,发现功能依旧有效

C#
[AddINotifyPropertyChangedInterface] public class Person { [AlsoNotifyFor("Name")] public string FirstName { get; set; } //当FirstName或LastName改变时,通知Name [AlsoNotifyFor("Name")] public string LastName { get; set; } public string Name { get; set; } public int Age { get; set; } [DoNotNotify] public string Department { get; set; } //不通知 }

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!