如何在 if 语句中使用占位符来访问属性

杰夫史密斯21

我不想使用大量 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 中的值。

sjb-sjb

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

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");

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章