C# 如何在if语句中使用占位符访问属性
我不想使用很多if语句来确定需要访问哪个属性,而是想知道是否可以使用占位符之类的东西 我试图用占位符编码一些东西,这就是我遇到问题的地方C# 如何在if语句中使用占位符访问属性,c#,json,discord.net,C#,Json,Discord.net,我不想使用很多if语句来确定需要访问哪个属性,而是想知道是否可以使用占位符之类的东西 我试图用占位符编码一些东西,这就是我遇到问题的地方 if(rootObject.permissions.{commandGroup}.{commandName}) { //做点什么 } 这将允许访问的属性根据commandGroup和commandName中字符串的值进行更改,而无需在JSON扩展时使用几个if语句 下面是if语句的问题: //Command是Discord.Net中CommandInfo的
if(rootObject.permissions.{commandGroup}.{commandName})
{
//做点什么
}
这将允许访问的属性根据commandGroup和commandName中字符串的值进行更改,而无需在JSON扩展时使用几个if语句
下面是if语句的问题:
//Command是Discord.Net中CommandInfo的实例
字符串commandGroup=command.Module.Group;
string commandName=command.Name;
if(rootObject.permissions.commandGroup.commandName)
{
//做点什么
}
以下是JSON文件在类中的存储方式:
内部类RootObject
{
公共权限权限{get;set;}
公共整数点{get;set;}
}
内部类权限
{
公共响应{get;set;}
}
内部班级反应
{
公共bool ping{get;set;}
公共布尔helloWorld{get;set;}
}
例如,如果commandGroup是Response,commandName是ping,我如何使用if语句来确定rootObject.permissions.Response.ping中存储的值是否正确。您可以使用反射来执行此操作,如下所示:
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));
}
}
公共静态类权限{
公共静态commandt组(此权限,字符串CommandGroup)
{
PropertyInfo commandGroupProperty=typeof(权限)。GetProperty(commandGroup);
return(T)(commandGroupProperty.GetValue(permissions));
}
公共静态bool CommandProperty(此命令组,字符串CommandProperty)
{
PropertyInfo commandPropertyProperty=typeof(T).GetProperty(commandProperty);
返回(bool)(commandPropertyProperty.GetValue(commandGroup));
}
}
那么你会这样使用它:
bool result = rootObject.permissions.CommandGroup<Response>( "response").CommandProperty( "ping");
bool result=rootObject.permissions.CommandGroup(“response”).CommandProperty(“ping”);
提示:类中的属性使用大写名称,参数使用小写名称 您想要访问的属性似乎都是
bool
。您可以将它们全部存储在字典中
:
您可以检查commandGroup的类型,并执行该操作。Ex
if(commandGroup.GetType()==typeof(Response))
internal class RootObject
{
public Dictionary<string, bool> permissions { get; set; } = new Dictionary<string, bool> {
{ "response.ping", false },
{ "response.helloworld", false },
// add more here...
};
public int points { get; set; }
}
if (rootObject.permissions[$"{commandGroup}.{commandName}"])