各种方式实现的编程不再赘述,分为动态和静态两种,动态需要virtul
动态加入商业版postsharp,开源版fody
下面主要介绍fody的使用
PropertyChanged.Fody
- vs2019-工具-NuGet包管理器-程序包管理器控制台/管理解决方案的NuNet平台
- 输入Install-Package PropertyChanged.Fody/平台搜索PropertyChanged.Fody并安装
- 配置文件FodyWeavers.xml自动生成
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd"> <Costura /> <MethodDecorator /> <PropertyChanged/> </Weavers>
- 官方示例代码示例(做出event事件响应就行了)
public class Person : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; //实现这个玩意就行了 [DoNotNotify] //不需要注册的 public string GivenNames { get; set; } [DependsOn("GivenName", "FamilyName")] //依赖属性 public string FamilyName { get; set; } public string FullName => $"{GivenNames} {FamilyName}"; }
MethodDecorator.Fody
1,安装方式相同,Install-Package MethodDecorator.Fody/平台搜索MethodDecorator.Fody并安装
2,配置文件FodyWeavers.xml和AssemblyInfo.cs
FodyWeavers.xml:
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<Costura />
<MethodDecorator />
<PropertyChanged/>
</Weavers>
AssemblyInfo.cs
using System;
using System.Collections.Generic;
using System.Text;
using System;
using TestDemo;
[module: FodyTest] //相当于注册类
3,代码
[AttributeUsage(AttributeTargets.All)] //可以分为对属性,方法,域等注解,all就是全部都注解
public class FodyTestAttribute : Attribute
{
protected object InitInstance;
protected MethodBase InitMethod;
protected Object[] Args;
public void Init(object instance, MethodBase method, object[] args)
{
InitMethod = method;
InitInstance = instance;
Args = args;
}
public void OnEntry()
{
Console.WriteLine("Before");
}
public void OnExit()
{
Console.WriteLine("After");
}
public void OnException(Exception exception)
{
}