Ari*_*ian 20 c# reflection c#-4.0
我在一个名为"A7" 的refrenced程序集(名为"DAL")中有一个静态类:
A7是这样的:
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";
}
Run Code Online (Sandbox Code Playgroud)
如何从DAL汇编A7类获取所有属性名称和值?
谢谢
Ada*_*rth 35
使用反射,你需要寻找字段; 这些不是属性.从下面的代码中可以看出,它查找公共静态成员:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用此语法获取属性时遇到相同的问题(其中“ ConfigValues”是具有静态属性的静态类,并且我正在寻找名称为“ LookingFor”的属性)
PropertyInfo propertyInfo = ConfigValues.GetType().GetProperties().SingleOrDefault(p => p.Name == "LookingFor");
Run Code Online (Sandbox Code Playgroud)
解决方案是改用typeof运算符
PropertyInfo propertyInfo = typeof(ConfigValues).GetProperties().SingleOrDefault(p => p.Name == "LookingFor");
Run Code Online (Sandbox Code Playgroud)
有效,您不必将其视为字段
高温超导
正如您在第一个问题中注意到的那样,您还混淆了属性和字段。您声明的是字段,而不是属性
所以这个变体应该可以工作:
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14794 次 |
| 最近记录: |