0%

c#特性参数

可以通过反射获取这些特性然后做处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Program
{
static void Main(string[] args)
{
var message = new MessageData {

Header="header...",
Body="body....",
Footer="footer...",
};

Type objT = typeof(Program);
Type fromBodyT = typeof(FromBodyAttribute);
MethodInfo method = objT.GetMethod("Test");

ParameterInfo[] paramsInfo = method.GetParameters();
var parameters= new List<object>(paramsInfo.Length);
foreach (ParameterInfo parameterInfo in paramsInfo)
{
var parameter = new object();
if (parameterInfo.CustomAttributes.Any(i => i.AttributeType == fromBodyT))
parameter = message.Body;
parameters.Add(parameter);
}


object result = method.Invoke(null, parameters.ToArray());
Console.WriteLine(result);


}
public class FromBodyAttribute : Attribute
{
}
public static string Test([FromBody] string body)
{
return body;
}
class MessageData
{

public string Body { get; set; }
public string Header { get; set; }
public string Footer { get; set; }

}

}