C# MethodInfo IsDefined
Description
MethodInfo IsDefined
When overridden in a derived class,
indicates whether one or more attributes of the specified type or of its derived
types is applied to this member.
Syntax
MethodInfo.IsDefined
has the following syntax.
public abstract bool IsDefined(
Type attributeType,
bool inherit
)
Parameters
MethodInfo.IsDefined
has the following parameters.
attributeType
- The type of custom attribute to search for. The search includes derived types.inherit
- true to search this member's inheritance chain to find the attributes; otherwise, false. This parameter is ignored for properties and events; see Remarks.
Returns
MethodInfo.IsDefined
method returns true if one or more instances of attributeType or any of its derived types
is applied to this member; otherwise, false.
Example
using System;//from w ww. j ava 2 s. co m
using System.Reflection;
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
private string myName;
public MyAttribute(string name)
{
myName = name;
}
public string Name
{
get
{
return myName;
}
}
}
public class MyClass1
{
[MyAttribute("This is an example attribute.")]
public void MyMethod(int i)
{
return;
}
}
public class MemberInfo_GetCustomAttributes_IsDefined
{
public static void Main()
{
Type myType = typeof(MyClass1);
MemberInfo[] myMembers = myType.GetMembers();
for(int i = 0; i < myMembers.Length; i++)
{
if(myMembers[i].IsDefined(typeof(MyAttribute), false))
{
Object[] myAttributes = myMembers[i].GetCustomAttributes(typeof(MyAttribute), false);
Console.WriteLine(myMembers[i]);
for(int j = 0; j < myAttributes.Length; j++)
Console.WriteLine(((MyAttribute)myAttributes[j]).Name);
}
}
}
}
The code above generates the following result.