How to get fields and their values from a static c

2020-02-26 14:57发布

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

6条回答
Viruses.
2楼-- · 2020-02-26 15:29

Just add a reference to the DAL.dll(or whatever you've called it) file and include it in the using section. Then you should be able to acces the public fields.

查看更多
在下西门庆
3楼-- · 2020-02-26 15:46

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();
        }
    }
查看更多
兄弟一词,经得起流年.
4楼-- · 2020-02-26 15:52

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

查看更多
戒情不戒烟
5楼-- · 2020-02-26 15:53

somthing like this: ?

FieldInfo[] fieldInfos = typeof(A7).GetFields(BindingFlags.Static | BindingFlags.Public);
查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-02-26 15:56

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
}
查看更多
Lonely孤独者°
7楼-- · 2020-02-26 15:56
 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>();
    }
查看更多
登录 后发表回答