考虑以下代码,有没有办法遍历对象树并确定所有方法的进度、它们的权重和总体成本?
假设我有一个自定义注释:
public enum ProgressWeight
{
ExtraLight,
Light,
Medium,
Heavy,
ExtraHeavy
}
[AttributeUsage(AttributeTargets.Method)]
public class Progressable : Attribute
{
public ProgressWeight Weight { get; set; }
public Progressable(ProgressWeight weight)
{
this.Weight = weight;
}
}
我想这样实现它:
public class Sumathig
{
Foo CompositionObject;
[Progressable(ProgressWeight.Light)]
public void DoSomethingLight()
{
\Do something that takes little time
}
[Progressable(ProgressWeight.ExtraHeavy)]
public void DoSomeIntesiveWork()
{
CompositionObject = new Foo();
CompositionObject.DoWork();
CompositionObject.DoMoreWork();
}
}
class Foo
{
[Progressable(ProgressWeight.Medium)]
public void DoWork()
{
\Do some work
}
[Progressable(ProgressWeight.Heavy)]
public void DoSomeMoreWork()
{
\Do more work
}
}
选项 1 - 注释
您提供的示例建议您应该查看:
- MSDN:反射
- MSDN:创建自定义属性
此方法使您能够使用可在运行时检索的元数据批注代码。 整个过程相对简单。 有关反射的示例,请查看:
- 代码项目:.NET 中的反射
附加阅读
- O'Reilly: Programming in C# (作者: Jesse Liberty)
- .NET 反射的"成本"是多少?
选项 2
另一种方法是支持组合并将所需的元数据公开为其中一个类的属性。 这可能适用于插件样式的体系结构。