Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/111.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 4.0 自动运行方法的C#属性_C# 4.0_Custom Attributes - Fatal编程技术网

C# 4.0 自动运行方法的C#属性

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

我不确定这是否完全可能。但我想做的是创建一个属性,当我调用一个run方法时,所有具有特定run属性的方法都会被运行。我意识到这可以通过代理来完成,但我觉得如果可以通过属性来实现的话,看起来可能会更干净一些。我应该注意到,运行顺序并不重要

基本设计:

//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);

您需要使用反射…查找每个方法或属性的属性,然后通过调用属性的方法和方法本身来执行它。您需要使用反射…查找每个方法或属性的属性,然后通过调用属性的方法和方法本身来执行它。