首页 > 解决方案 > 如何在 if 语句中使用占位符来访问属性

问题描述

我不想使用大量 if 语句来确定需要访问哪个属性,而是想知道是否可以使用诸如占位符之类的东西。

我试图用占位符编写一些东西,这就是我遇到问题的地方。

if (rootObject.permissions.{commandGroup}.{commandName})
{
    //do something                
}

这将允许访问的属性根据 commandGroup 和 commandName 中的字符串值进行更改,而不必在 JSON 扩展时使用多个 if 语句。

这是 if 语句的问题:


//Command is an instance of CommandInfo from Discord.Net
string commandGroup = command.Module.Group;
string commandName = command.Name;


if (rootObject.permissions.commandGroup.commandName)
{
    //do something
}

以下是 JSON 文件在类中的存储方式:

    internal class RootObject
    {
        public Permissions permissions { get; set; }
        public int points { get; set; }
    }
    internal class Permissions
    {
        public Response response { get; set; }
    }
    internal class Response
    {
        public bool ping { get; set; }
        public bool helloWorld { get; set; }
    }

例如,如果 commandGroup 是 Response 并且 commandName 是 ping,我将如何使用 if 语句来确定是否存储在 rootObject.permissions.response.ping 中的值。

标签: c#jsondiscord.net

解决方案


您可以使用反射来做到这一点,如下所示:

public static class PermissionsExtensions {
    public static T CommandGroup<T>(this Permissions permissions, string commandGroup)
    {
         PropertyInfo commandGroupProperty = typeof(Permissions).GetProperty(commandGroup);
         return (T)(commandGroupProperty.GetValue( permissions));
    }
    public static bool CommandProperty<T>(this T commandGroup, string commandProperty) 
    {
        PropertyInfo commandPropertyProperty = typeof(T).GetProperty( commandProperty);
        return (bool)(commandPropertyProperty.GetValue( commandGroup));
    }
}

然后你会像这样使用它:

bool result = rootObject.permissions.CommandGroup<Response>( "response").CommandProperty( "ping");

提示:类中的属性使用大写名称,参数使用小写名称。


推荐阅读