Utility 文件夹下的 Guard 类是一个帮助类,该类只在 ObjectBuilder 项目内可见,主要执行一下验证工作。
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
using System.Globalization;
5
using System.Reflection;
6
using Microsoft.Practices.ObjectBuilder.Properties;
7![](/Images/OutliningIndicators/None.gif)
8
namespace Microsoft.Practices.ObjectBuilder
9![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
10![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
11
/// "验证函数" 的帮
12
/// 助类。
13
/// </summary>
14
internal static class Guard
15![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
16![](/Images/OutliningIndicators/InBlock.gif)
17![](/Images/OutliningIndicators/ContractedSubBlock.gif)
公有方法#region 公有方法
18![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
19
/// 验证 assignee 类
20
/// 型的引用是否可以
21
/// 指向 providedType
22
/// 类型的实例。
23
/// </summary>
24
/// <param name="assignee">
25
/// "引用变量" 的类
26
/// 型。
27
/// </param>
28
/// <param name="providedType">
29
/// "对象实例" 的类
30
/// 型。
31
/// </param>
32
/// <param name="classBeingBuilt">
33
/// 要使用 OB 块进行
34
/// 对象创建的对象类
35
/// 型。
36
/// </param>
37
public static void TypeIsAssignableFromType(
38
Type assignee,
39
Type providedType,
40
Type classBeingBuilt)
41![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
42
if (!assignee.IsAssignableFrom(providedType))
43![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
44
throw new IncompatibleTypesException(string.Format(CultureInfo.CurrentCulture, Resources.TypeNotCompatible, assignee, providedType, classBeingBuilt));
45
}
46
}
47![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
48
/// 验证指定函数的实
49
/// 参是否有效。
50
/// </summary>
51
/// <param name="methodInfo">
52
/// 函数的元数据。
53
/// </param>
54
/// <param name="parameters">
55
/// 函数的实参。
56
/// </param>
57
/// <param name="typeBeingBuilt">
58
/// 要使用 OB 块进行
59
/// 对象创建的对象类
60
/// 型。
61
/// </param>
62
public static void ValidateMethodParameters(
63
MethodBase methodInfo,
64
object[] parameters,
65
Type typeBeingBuilt)
66![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
67
ParameterInfo[] paramInfos = methodInfo.GetParameters();
68![](/Images/OutliningIndicators/InBlock.gif)
69
for (int i = 0; i < paramInfos.Length; i++)
70![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
71
if (parameters[i] != null)
72![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
73
Guard.TypeIsAssignableFromType(paramInfos[i].ParameterType, parameters[i].GetType(), typeBeingBuilt);
74
}
75
}
76
}
77
#endregion
78![](/Images/OutliningIndicators/InBlock.gif)
79
}
80
}
81![](/Images/OutliningIndicators/None.gif)