c# - 是否可以从 C# 中的字符串创建属性?
问题描述
我在 C# 中有一个字符串列表,我想遍历列表并将列表中的每个项目添加为我的类的属性。例如:
public class test
{
List<string> inputList = new List<string> {"add", "subtract", "multiply"};
foreach(var val in inputList)
{
//code to convert string to property
}
}
在我运行上面的代码之后,当我创建一个新的类测试对象时,我想得到:test.add 或 test.subtract 等,我应该能够为这些属性赋值。
这可能吗?如果是的话,有人可以建议这样做的最佳方法吗?
从上面继续,这里的目的是添加 API。这里的列表是动态加载的。我应该以更贴切的列表为例。
public class test
{
List<string> inputList = new List<string> {"name", "age", "dob"};
foreach(var val in inputList)
{
//code to convert string to property of the class test
}
}
代码运行后,我应该能够将值分配给姓名、年龄和出生日期作为用户输入,即
test.name = "blah"
test.age = "123"
由于列表是动态更新的,因此列表中的项目(及其数量)会有所不同。列表中的所有项目都必须添加为类测试的属性,并且用户应该能够在运行时为这些属性分配值。
解决方案
您可以使用dynamic
来实现这一点。虽然了解它的概念以及如何使用它是非常好的dynamic
,但它会扼杀使用强类型语言和编译时检查的好处,并且应该只在替代方案更痛苦时使用:
List<string> inputList = new List<string> {"add", "subtract", "multiply"};
var builder = new System.Dynamic.ExpandoObject() as IDictionary<string, Object>;
foreach(var val in inputList)
{
builder.Add(val, $"{val}: some value here");
}
var output = (dynamic)builder;
Console.WriteLine(output.add);
Console.WriteLine(output.subtract);
Console.WriteLine(output.multiply);
推荐阅读
- oracle - 从数据泵实用程序导入的表的大小和行数比导出的少?
- apache-kafka - kafka 支持百万分区吗?
- content-management-system - Contao CMS 安装后出现 404“找不到页面”错误
- laravel - 突然的 VueJS 错误:多 vue 中的错误,找不到模块:错误:无法解析中的“vue”
- php - 我在使用 PDO 准备列名作为参数时遇到问题
- reactjs - 将 jQuery 代码翻译成原生 JavaScript
- mysql - 更新行时获取“子查询返回超过 1 行”-MariaDB
- java - RecyclerView:没有附加适配器;跳过布局和 java.lang.NullPointerException
- git - 为什么我的 git 客户端无法将 png/tar/jpg 类型的文件推送/上传到 repo
- javascript - 使用两个排序条件对javascript中的对象数组进行排序