在《上篇》中,我比较了三种属性操作的性能:直接操作,单纯通过PropertyInfo反射和IL Emit。本篇继续讨论这个话题,我们再引入另外两种额外的属性操作方式:Expression Tree(这和IL Emit基本一致)和通过Delegate的静态方法CreateDelegate创建相应的委托进行属性的赋值和取值。[源代码从这里下载]

目录
一、定义测试相关的接口、类型和委托
二、通过Expression Tree的方式创建用于属性操作的委托
三、编写属性赋值操作测试方法
四、编写属性取值操作测试方法
五、执行测试程序,查看测试结果
六、如果在Expression Tree中避免类型转换呢?

我首先定义了一个Bar类型和IFoo接口,该接口中仅仅包含一个类型和名称为Bar的可读写属性。Foo1、Foo2和Foo3均实现接口IFoo,这些接口和类型定义如下:

class Bar{ }
interface IFoo
   3: {
   4:     Bar Bar { get; set; }
   5: }
class Foo1 : IFoo
   7: {
public Bar Bar { get; set; }
   9: }
class Foo2 : IFoo
  11: {
public Bar Bar { get; set; }
  13: }
class Foo3 : IFoo
  15: {
public Bar Bar { get; set; }
  17: }

相关文章:

  • 2022-01-07
  • 2022-03-03
  • 2021-09-25
  • 2022-12-23
  • 2021-12-13
  • 2021-06-13
猜你喜欢
  • 2022-12-23
  • 2021-10-03
  • 2021-07-13
  • 2021-11-20
  • 2021-06-21
  • 2022-12-23
相关资源
相似解决方案