我写了一些代码来获得实现接口的所有类。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");
}
}
请提供[mcve] - 您提供的许多代码都不相关(例如,用于查找接口实现的代码),但是您没有提供足够的信息让我们实际运行并查看问题。 (我也建议在控制台应用程序中演示这一点 - 我非常怀疑WPF在这里是相关的。) –
@JonSkeet应该由此代码提供的类arre UserControls来自WPF – itskajo
仅仅因为这就是它们如何用于您的应用程序并不意味着他们需要成为“UserControl”类来演示问题。当你问一个关于堆栈溢出的问题时,你应该尽可能地减少它 - 这是你在问一个问题之前你应该做的诊断工作的一部分,这通常意味着你不需要问这个问题所有。 –