c# - 如何在 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 中的值。
解决方案
您可以使用反射来做到这一点,如下所示:
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");
提示:类中的属性使用大写名称,参数使用小写名称。
推荐阅读
- sql - SQL 如何从本月至今的表中计算单日损益
- julia - 将 excel 文件添加到 Julia MacOS
- android - 从终端运行的颤振工作,而手动不工作
- php - 按时间戳排序,然后将某些元素设置为第一
- html - thead,tbody 显示块和同步的列和标题
- scheduled-tasks - Kentico 11 计划任务不会在自定义类中运行
- php - CodeIgniter 4 request.getVar 函数不起作用
- javascript - 我正在尝试制作一个 chrome 扩展来打开一个选项卡,然后运行一个 URL 列表,在加载时依次打开每个选项卡中的下一个
- java - 提取基础模型预测 H2o 堆叠模型 mojo
- postgresql - 试图在 GCP 上的 postgres 数据库中创建我的第一个表,但没有任何反应