【发布时间】:2014-03-10 01:31:40
【问题描述】:
考虑以下代码,有没有办法遍历对象树并确定所有方法的进度、它们的权重和总成本?
假设我有一个自定义注释:
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
}
}
【问题讨论】:
-
如果您遍历类的
Types 或所涉及方法的Expressions 的数组,您应该能够做到这一点......虽然看起来有点混乱。 -
annotation在这种情况下是错误的词。修复标签。他们是attributes。 -
如果你有关于
type(metadata) 的信息,那么你就有了所有你需要的信息。使用反射。 -
他最有可能知道如何访问元数据,他想要的是遍历类树。除非您使用 Roslyn 之类的东西,否则我认为这是不可能的。
-
如果我必须使用编译器,我不太可能走这条路。我需要权衡方法并通过事件展示进度。
标签: c# annotations