在 C# 中使用变量分配 属性?

using a variable to assign a property in c#?

我在 C# 应用程序的设置中设置了一些属性。我正在使用它们来存储字符串。我的问题是我想根据 class 的名称变量来调用它们。

所以我想做这样的事情

Description = Properties.Settings.Default.(name + "Description");

这可能吗?或者我是否必须根据名称 属性?

编写令人讨厌的 switch 语句
Swith(name)
case:name1 
 Description = properties.settings.default.name1Descrition;

假设你说的是Winforms,Properties.Settings.Default是一个可索引的集合,所以你只需要按键获取即可:

var Description = Properties.Settings.Default[name + "Description"] as string;

您不需要使用反射,任何一种方式都可以检索它。您的第一个猜测很接近。

使用索引器始终获取值 returns 和 object,因此您需要将其转换为最终类型(as string)或任何类型 属性是。