1 // ***********************************************************************
2 // Copyright (c) 2008 Charlie Poole
4 // Permission is hereby granted, free of charge, to any person obtaining
5 // a copy of this software and associated documentation files (the
6 // "Software"), to deal in the Software without restriction, including
7 // without limitation the rights to use, copy, modify, merge, publish,
8 // distribute, sublicense, and/or sell copies of the Software, and to
9 // permit persons to whom the Software is furnished to do so, subject to
10 // the following conditions:
12 // The above copyright notice and this permission notice shall be
13 // included in all copies or substantial portions of the Software.
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 // ***********************************************************************
25 #define NUNIT_FRAMEWORK
30 using System.Reflection;
32 namespace NUnit.Compatibility
35 /// Provides a platform-independent methods for getting attributes
36 /// for use by AttributeConstraint and AttributeExistsConstraint.
38 public static class AttributeHelper
41 /// Gets the custom attributes from the given object.
43 /// <remarks>Portable libraries do not have an ICustomAttributeProvider, so we need to cast to each of
44 /// it's direct subtypes and try to get attributes off those instead.</remarks>
45 /// <param name="actual">The actual.</param>
46 /// <param name="attributeType">Type of the attribute.</param>
47 /// <param name="inherit">if set to <c>true</c> [inherit].</param>
48 /// <returns>A list of the given attribute on the given object.</returns>
49 public static Attribute[] GetCustomAttributes(object actual, Type attributeType, bool inherit)
52 var attrProvider = actual as ICustomAttributeProvider;
53 if (attrProvider == null)
54 throw new ArgumentException(string.Format("Actual value {0} does not implement ICustomAttributeProvider.", actual), "actual");
56 return (Attribute[])attrProvider.GetCustomAttributes(attributeType, inherit);
58 var member = actual as MemberInfo;
61 return (Attribute[])member.GetCustomAttributes(attributeType, inherit);
64 var param = actual as ParameterInfo;
67 return (Attribute[])param.GetCustomAttributes(attributeType, inherit);
70 var assembly = actual as Assembly;
73 return (Attribute[])assembly.GetCustomAttributes();
76 throw new ArgumentException(string.Format("Actual value {0} must be a MemberInfo, ParameterInfo or Assembly.", actual), "actual");