Search public and static fields in CSharp

Description

The following code shows how to search public and static fields.

Example


/*from  w  ww . jav  a 2  s .co  m*/
using System;
using System.Reflection;

class AttributesSample
{
    public void Mymethod (int int1m, out string str2m, ref string str3m)
    {
        str2m = "in Mymethod";
    }

    public static int Main(string[] args)
    {      
        Type MyType = Type.GetType("AttributesSample");

        MethodBase Mymethodbase = MyType.GetMethod("Mymethod");

        Console.WriteLine("Mymethodbase = " + Mymethodbase);

        MethodAttributes Myattributes = Mymethodbase.Attributes;

        PrintAttributes(typeof(System.Reflection.MethodAttributes), (int) Myattributes);
        return 0;
    }
    public static void PrintAttributes(Type attribType, int iAttribValue)
    {

        FieldInfo[] fields = attribType.GetFields(BindingFlags.Public | BindingFlags.Static);
        for (int i = 0; i < fields.Length; i++)
        {
            int fieldvalue = (Int32)fields[i].GetValue(null);
            if ((fieldvalue & iAttribValue) == fieldvalue)
            {
                Console.WriteLine(fields[i].Name);
            }
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Reflection »




Array
Constructor
Event
Field
Interface
Method
Properties
Type