C# 如何从引用程序集中的静态类获取字段及其值

C# 如何从引用程序集中的静态类获取字段及其值,c#,reflection,c#-4.0,C#,Reflection,C# 4.0,我在一个名为“A7”的引用程序集中(名为“DAL”)有一个静态类: 像这样: 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"; pu

我在一个名为“A7”的引用程序集中(名为“DAL”)有一个静态类:

像这样:

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";
}
如何从DALassemby A7类获取所有属性名称和值


谢谢

只需添加对DAL.dll(或您所称的任何文件)的引用,并将其包含在使用部分。然后您应该能够访问公共字段。

使用反射,您需要查找字段;这些不是财产。从以下代码中可以看到,它查找公共静态成员:

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();
    }
}
见或问

正如您在第一个问题中所注意到的,您还混淆了属性和字段。您声明的是字段,而不是属性

因此,这种方法的一种变体应该是可行的:

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
}
像这样的事:

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

当我尝试使用此语法获取属性时,我遇到了相同的问题(其中“ConfigValues”是一个具有静态属性的静态类,我正在寻找一个名为“LookingFor”的属性)

解决方法是使用typeof操作符

PropertyInfo propertyInfo = typeof(ConfigValues).GetProperties().SingleOrDefault(p => p.Name == "LookingFor");
这是可行的,您不必将它们视为字段

HTH

公共静态IEnumerable GetAll(),其中T:class
{
var fields=typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
返回字段。选择(f=>f.GetValue(null)).Cast();
}

不要认为我的班级在另一个班级。assembly@Nima这个问题清楚地说明了“在引用程序集中”,因此假设您使用了相关的
语句,那么它就可以工作了。这是用于名称,而不是用于值!不要认为我的类在另一个集合中,GET值需要一个实例,但是A7是静态的。@ PvIt在静态类上,通过<代码> null < /C>。我的错。但是在运行时,您无法获取公开声明字段的所有名称。这就是为什么要使用反射。
PropertyInfo propertyInfo = typeof(ConfigValues).GetProperties().SingleOrDefault(p => p.Name == "LookingFor");
 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>();
    }