C# 反射:静态 属性 NullPointer

C# Reflection: Static Property NullPointer

我写了一些代码来让所有 类 实现一个接口。

private static List<ClassNameController> getClassesByInheritInterface(Type interfaceName)
{

        var types = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s => s.GetTypes())
            .Where(p => interfaceName.IsAssignableFrom(p) && !p.IsInterface);
        List<ClassNameController> myControllerList = new List<ClassNameController>();
        foreach (System.Type type in types)
        {
            // Get a PropertyInfo of specific property type(T).GetProperty(....)
            PropertyInfo propertyInfo;
            propertyInfo = type
                .GetProperty("className", BindingFlags.Public | BindingFlags.Static);

            // Use the PropertyInfo to retrieve the value from the type by not passing in an instance
            object value = propertyInfo.GetValue(null, null);

            // Cast the value to the desired type
            string typedValue = (string)value;

            myControllerList.Add(new ClassNameController(typedValue, type));
        }

        return myControllerList;
    }
}

所有这些 类 都得到了 public static string className 属性。这个 属性 的值我用来创建一个 ClassNameController 实例

class ClassNameController
{
    public string Name { get; set; }
    public System.Type ObjectType { get; set; }

    public ClassNameController(string name, Type objectType)
    {
        this.Name = name;
        this.ObjectType = objectType;
    }

    public override string ToString()
    {
        return Name;
    }
}

但是当我开始我的程序时它在

崩溃了
object value = propertyInfo.GetValue(null, null);

带有错误消息

System.NullReferenceException.

问题:为什么他找不到属性类名?

编辑: 所有 类 实现这些接口的都是 WPF 用户控件。 例如 IModuleview:

  internal interface IModuleView
{
    void updateShownInformation();

    void setLanguageSpecificStrings();
}

这里有一个模块示例:

   public partial class DateBox : UserControl, IModuleView
{
    public static string className = "Datebox";
    public DateBox()
    {
        InitializeComponent();
    }

    public void setLanguageSpecificStrings()
    {
        this.ToolTip = DateTime.Now.ToString("dddd, dd.MM.yy");
    }

    public void updateShownInformation()
    {
        tbDate.Text = DateTime.Now.ToString("ddd-dd");
    }
}

So why cant he find the Property Classname?

查看您发布的声明 class DateBox:

public static string className = "Datebox";

它有 field

的签名

因此您应该使用 GetField 方法:

object value = type.GetField("className", 
             System.Reflection.BindingFlags.Public | 
             System.Reflection.BindingFlags.Static).GetValue(null);

解释:What is the difference between a Field and a Property in C#?