从嵌套类属性中获取布尔值

问题描述 投票:0回答:1

我正在尝试使用PropertyInfo的

GetValue()
方法,但它似乎不起作用。

public bool IsDeviceOperable(ServiceType type, bool isServer, string domain)
{
    string settingsFileContent = _fileReader.Read(_filePathProvider.GetSettingsFilePath());

    var settings = _jsonDeserializer.Deserialize<Settings>(settingsFileContent);
    var settingsName = GetSettingsNameByType(type);

    string deviceType = GetDeviceType(isServer);

    var info = settings.GetType().GetProperty(domain.ToUpper())
        .PropertyType.GetProperty(settingsName)
        .PropertyType.GetProperty(deviceType);


    bool value = (bool)info.GetValue(settings, null);

    return value;
}

它抛出

System.Reflection.TargetException:“对象与目标类型不匹配。”

我的设置文件如下所示:

public class Settings
{
    public FirstDomain First { get; set; }
    public SecondDomain Second { get; set; }
    ...
}

域类如下所示:

public class FirstDomain
{
    public Settings1 firstSettings { get; set; }
    public Settings2 secondSettings { get; set; }
    ...
}

public class SecondDomain
{
    public Settings1 firstSettings { get; set; }
    public Settings2 secondSettings { get; set; }
    ...
}

设置类如下所示:

public class Settings1
{
    public bool RunOnClient { get; set; }
    public bool RunOnServer { get; set; }
}

public class Settings2
{
    public bool RunOnClient { get; set; }
    public bool RunOnServer { get; set; }
}

第一域第二域是有原因的,而且设置也不同,为了更容易理解,我重新命名了它们。

c# reflection nested propertyinfo
1个回答
2
投票

问题在于代码创建了嵌套属性的属性信息,但提供了父对象的实例。属性信息始终对定义该属性的类型的实例进行操作。

因此,您必须先获取父实例,然后在正确的实例上调用属性:

var settings = _jsonDeserializer.Deserialize<Settings>(settingsFileContent);
var settingsName = GetSettingsNameByType(type);

string deviceType = GetDeviceType(isServer);

var domainProp = settings.GetType().GetProperty(domain.ToUpper());
var domainInst = domainProp.GetValue(settings, null);
var settingsProp = domainProp
    .PropertyType.GetProperty(settingsName);
var settingsInst = settingsProp.GetValue(domainInst, null);
var deviceTypeProp = settingsProp
    .PropertyType.GetProperty(deviceType);

bool value = (bool)deviceTypeProp.GetValue(settingsInst, null);
© www.soinside.com 2019 - 2024. All rights reserved.