2017-02-23 118 views
1

我写了一些代码来获得实现接口的所有类。C#反射:静态属性空指针

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崩溃。

问题:为什么他不能找到Property Classname?

编辑: 所有实现这些接口的类都是WPF UserControls。 例如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"); 
    } 
} 
+0

请提供[mcve] - 您提供的许多代码都不相关(例如,用于查找接口实现的代码),但是您没有提供足够的信息让我们实际运行并查看问题。 (我也建议在控制台应用程序中演示这一点 - 我非常怀疑WPF在这里是相关的。) –

+0

@JonSkeet应该由此代码提供的类arre UserControls来自WPF – itskajo

+1

仅仅因为这就是它们如何用于您的应用程序并不意味着他们需要成为“UserControl”类来演示问题。当你问一个关于堆栈溢出的问题时,你应该尽可能地减少它 - 这是你在问一个问题之前你应该做的诊断工作的一部分,这通常意味着你不需要问这个问题所有。 –

回答

2

那么为什么不能,他找到物业类名?

在您发布的类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#?

+0

我编辑了一个例子的问题。你能解释一下Field和Property之间的区别在哪里吗? – itskajo

+0

社区可以;) –

+0

这解决了我的问题:)谢谢:) – itskajo