简体   繁体   English

是否可以从 C# 中的字符串创建属性?

[英]Is it possible to create a property from a string in C#?

I have a list of strings in C# and I want to loop through the list and add each item of the list as a property of my class.我在 C# 中有一个字符串列表,我想遍历列表并将列表中的每个项目添加为我的类的属性。 For eg:例如:

public class test
{
 List<string> inputList = new List<string> {"add", "subtract", "multiply"};
 foreach(var val in inputList)
 {
   //code to convert string to property
 }
}

After I run the above code, when I create a new object of class test, I would like to get: test.add or test.subtract etc. and I should be able to assign values to these properties.运行上面的代码后,当我创建类 test 的新对象时,我想得到:test.add 或 test.subtract 等,我应该能够为这些属性赋值。

Is this possible?这可能吗? If yes, could someone please suggest the best way of doing this?如果是的话,有人可以建议这样做的最佳方法吗?

Continuing from above, the aim here is to add API.从上面继续,这里的目的是添加 API。 The list here is dynamically loaded.这里的列表是动态加载的。 I should have started with a more apt list as an example.我应该从一个更贴切的列表开始作为例子。

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
     }
    }

After the code is run I should be able to assign values to name, age and dob as user inputs ie代码运行后,我应该能够将值分配给 name、age 和 dob 作为用户输入,即

test.name = "blah"
test.age = "123"

Since the list is dynamically updated, the items (and their number) in the list will vary.由于列表是动态更新的,列表中的项目(及其数量)会有所不同。 All the items in the list have to be added as a property of the class test and the user should be able to assign values to those properties at run time.列表中的所有项目都必须作为类测试的属性添加,并且用户应该能够在运行时为这些属性赋值。

You can use dynamic to achieve this.您可以使用dynamic来实现这一点。 While it's very good to be aware of the concept of dynamic and how to use it, it kills the benefits of using a strongly typed language and compile time checking, and should really only be used when the alternative is more painful:虽然了解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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM