首页 > 解决方案 > 是否可以从 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"

由于列表是动态更新的,因此列表中的项目(及其数量)会有所不同。列表中的所有项目都必须添加为类测试的属性,并且用户应该能够在运行时为这些属性分配值。

标签: c#stringdynamicproperties

解决方案


您可以使用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);

推荐阅读