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
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();
}
}
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
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
}
somthing like this: ?
FieldInfo[] fieldInfos = typeof(A7).GetFields(BindingFlags.Static | BindingFlags.Public);
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.
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>();
}