C# 4.0 自动运行方法的C#属性
我不确定这是否完全可能。但我想做的是创建一个属性,当我调用一个run方法时,所有具有特定run属性的方法都会被运行。我意识到这可以通过代理来完成,但我觉得如果可以通过属性来实现的话,看起来可能会更干净一些。我应该注意到,运行顺序并不重要 基本设计:C# 4.0 自动运行方法的C#属性,c#-4.0,custom-attributes,C# 4.0,Custom Attributes,我不确定这是否完全可能。但我想做的是创建一个属性,当我调用一个run方法时,所有具有特定run属性的方法都会被运行。我意识到这可以通过代理来完成,但我觉得如果可以通过属性来实现的话,看起来可能会更干净一些。我应该注意到,运行顺序并不重要 基本设计: //This is the method called that should start off the attribute chain public void Run(){ //calling logic in here } [Automa
//This is the method called that should start off the attribute chain
public void Run(){
//calling logic in here
}
[AutomatedRun]
private void Method1(){
}
[AutomatedRun]
private void Method2(){
}
属性
只是元数据。除非你寻找它们并采取行动,否则它们是无用的。因此,在这种情况下,您需要使用反射
获取那些具有AutomatedRun
属性的方法,并调用它们:
var methods = typeof(YourClass)
.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(mi => Attribute.IsDefined(mi, typeof(AutomatedRunAttribute)));
foreach(var m in methods)
m.Invoke(yourInstance);
属性
只是元数据。除非你寻找它们并采取行动,否则它们是无用的。因此,在这种情况下,您需要使用反射
获取那些具有AutomatedRun
属性的方法,并调用它们:
var methods = typeof(YourClass)
.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(mi => Attribute.IsDefined(mi, typeof(AutomatedRunAttribute)));
foreach(var m in methods)
m.Invoke(yourInstance);
您需要使用反射…查找每个方法或属性的属性,然后通过调用属性的方法和方法本身来执行它。您需要使用反射…查找每个方法或属性的属性,然后通过调用属性的方法和方法本身来执行它。