How to get fields and their values from a static class in referenced assembly

22,252

Solution 1

Using reflection, you will need to look for fields; these are not properties. As you can see from the following code, it looks for public static members:

class Program
{
    static void Main(string[] args)
    {
        Type t = typeof(A7);
        FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public);

        foreach (FieldInfo fi in fields)
        {
            Console.WriteLine(fi.Name);
            Console.WriteLine(fi.GetValue(null).ToString());
        }

        Console.Read();
    }
}

Solution 2

I faced the same issue when i tried to get the properties using this syntax (where "ConfigValues" is a static class with static properties and I am looking for a property with the name "LookingFor")

PropertyInfo propertyInfo = ConfigValues.GetType().GetProperties().SingleOrDefault(p => p.Name == "LookingFor");

The solution was to use the typeof operator instead

PropertyInfo propertyInfo = typeof(ConfigValues).GetProperties().SingleOrDefault(p => p.Name == "LookingFor");

that works, you don't have to view them as fields

HTH

Solution 3

See this or this question.

As you will notice in the first question, you also mix up properties and fields. What you are declaring are fields, not properties

So a variant of this should work:

Type myType = typeof(MyStaticClass);
FieldInfo[] fields= myType.GetFields(
       BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
foreach (FieldInfo f in fields)
{
    // use f.Name and f.GetValue(null) here
}

Solution 4

somthing like this: ?

FieldInfo[] fieldInfos = typeof(A7).GetFields(BindingFlags.Static | BindingFlags.Public);

Solution 5

 public static IEnumerable<T> GetAll<T>() where T : class
    {
      var fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
       return fields.Select(f => f.GetValue(null)).Cast<T>();
    }
Share:
22,252
Arian
Author by

Arian

Please vote-up this thread: RDLC Report Viewer for Visual Studio 2022

Updated on April 07, 2020

Comments

  • Arian
    Arian about 4 years

    I have a static class in a refrenced assembly(named "DAL") named "A7":

    A7 like this:

    public static class A7
    {
    public static readonly bool NeedCoding = false;
    public static readonly string Title = "Desc_Title"
    public static readonly string F0 = "";
    public static readonly string F1 = "Desc_F1";
    public static readonly string F2 = "Desc_F2";
    public static readonly string F3 = "Desc_F3";
    public static readonly string F4 = "Desc_F4";
    }
    

    How I can get All Properties name and values from DAL assemby A7 class?

    thanks