是否可以使用PostSharp方面注入代码来读取/写入对象的属性?例如,请考虑以下类:
[ BinarySerializable ]
public class Employee {
public string Name {get; set; }
public string Title {get; set;}
}
在这种情况下,“BinarySerializable”将是一个自定义方面,它引入了一个自定义的“IBinarySerializable”接口,如下所示:
public interface IBinarySerializable
{
void Write(BinaryWriter writer);
void Read(BinaryReader reader);
}
编译后,生成的类看起来像这样:
public class Employee : IBinarySerializable
{
public string Name {get; set;}
public string Title {get; set; }
void IBinarySerializable.Write(BinaryWriter writer)
{
writer.Write(Name);
writer.Write(Title);
}
void IBinarySerializable.Read(BinaryReader reader)
{
Name = reader.ReadString();
Title = reader.ReadString();
}
}
直观地说,我觉得这应该可以使用PostSharp,但我需要一些正确的方法。如果这是可能的,那么如何处理由其他方面注入的属性?
UPDATE:我尝试使用内置的PSerializable方面创建一个简单的示例,但是当成员从没有该属性的.NET框架类继承时遇到了问题。
将[PSerializable]属性添加到EmployeeCollection类无法使用“无法应用[PSerializable]”来键入'AOPSerialization.EmployeeCollection',因为基类型没有[PSerializable]或[Serializer]属性。“
从EmployeeCollection类中省略[PSerializable]属性会抛出运行时的PortableSerializationException:无法找到类型为“AOPSerialization.EmployeeCollection”的序列化程序。
例如:
[PSerializable]
public class AOPComponent
{
public string Title { get; set; }
public string Description { get; set; }
public AOPComponent(string title, string description){...}
}
[PSerializable]
public class AOPComponentCollection<T> : ObservableCollection<T>
{...}
[PSerializable]
public class EmployeeCollection : AOPComponentCollection<Employee>
{...}
[PSerializable]
public class Company : AOPComponent
{
public EmployeeCollection Engineers { get; set; }
public EmployeeCollection Managers { get; set; }
}
我发现Serializer和ImportSerializer属性用于告诉PortableFormatter使用哪个自定义ISerializer或ISerializerFactory实现。
但问题仍然存在:
如何为通用基本集合类型指定自定义序列化程序?
此方法失败,因为属性可能不包含类型参数。
[PSerializable, ImportSerializer(typeof(ObservableCollection<T>), typeof(AOPComponentSerializerFactory))]
public class AOPComponentCollection<T> : ObservableCollection<T> where T : AOPComponent
{...}
此方法失败,因为PostSharp找不到ObservableCollection的序列化程序&lt; T&gt;
[PSerializable, Serializer(typeof(AOPComponentSerializerFactory))]
public class AOPComponentCollection<T> : ObservableCollection<T> where T : AOPComponent
{...}
答案 0 :(得分:1)
使用PostSharp可以做到这一点,但只能使用低级别的PostSharp SDK,它没有文档证明且不受支持。
好消息是我们已经在命名空间PostSharp.Serialization中为您实现了这一点。方面为[PSerializable]
,格式化程序为PortableFormatter
。