简体   繁体   中英

PropertyInfo.GetValue(null, null) returns null

i have a class with a static public property called "Info". via reflection i want to get this properties value, so i call:

PropertyInfo pi myType.GetProperty("Info");
string info = (string) pi.GetValue(null, null);

this works fine as long as the property is of type string. but actually my property is of type IPluginInfo and a PluginInfo type (implementing IPluginInfo) is instatiated and returned in the Info properties get accessor, like this:

public static IPluginInfo PluginInfo
{
    get 
    {
        IPluginInfo Info = new PluginInfo();
        Info.Name = "PluginName";
        Info.Version = "PluginVersion";
        return Info;
    }
}

like this when i call:

IPluginInfo info = pi.GetValue(null, null) as IPluginInfo;

info is always null, whiel PropertyInfo pi is still valid. am i missing something obvious here?

Could you create a short but complete program that demonstrates the problem?

Given that you're talking about plugins, my guess is that you've got the problem of having IPluginInfo defined in two different assemblies. See if this article helps at all.

The easiest way to verify it is to call pi.GetValue and store the result in an object variable first, then do the cast or "as" in another line. That way you can break the debugger and look at the return value before it's lost.

My first guess would be that you have re-declared the IPluginInfo interface. All .NET types are scoped by their assembly; if you have the same class file in 2 assemblies, you have 2 different interfaces that happen to have the same name.

ok, thanks for all the answers.

i indeed already had the plugininterface in a separate .dll but had placed this .dll in the pluginhosts directory as well as in the directory with all the plugins.

Um, first of all I'd implement that property a little differently:

private static PluginInfo _PluginInfo = null;
public static IPluginInfo PluginInfo
{
    get
    {
        if (_PluginInfo == null)
        {
           _PluginInfo = new PluginInfo();
           _PluginInfo.Name = "PluginName";
           _PluginInfo.Version = "PluginVersion";
        }
        return _PluginInfo;
    }
}

Note that this needs a little more work because it isn't threadsafe, but hopefully you get the idea: build it one time rather than repeatedly.

I'll stop here now, since it looks like two others already finished the rest of my answer while putting together the first part.

In C#, AS returns null if the value does not match the type. If you write:

object info = pi.GetValue(null, null);
Console.WriteLine(info.GetType().ToString());

what type do you receive?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM