如何使用FOR循环中的连接字符串访问对象属性

时间:2018-03-06 05:57:06

标签: c#

我有以下课程

class Names
{
    public string Name1 { get; set; }
    public string Name2 { get; set; }
    //.
    //.
    public string Name5 { get; set; }
}

我想访问FOR循环中的所有属性

for (int i = 1; i <= 5; i++)
{
   string varName = "Name";
   //concat string varName and variable i 
   //to access properties Name1, Name2 and so on..
}

有可能吗?

4 个答案:

答案 0 :(得分:3)

肯定 可能,但问题是,如果是可取的。您可以使用反射来实现您想要的效果

string concatenated = string.Empty;
for(int i = 1; i <= 5; i++)
{
    var variableName = $"Name{i}";
    var type = typeof(Names);

    var property = type.GetProperty(name);
    var value = property.GetValue(names);
    concatenated += value;
}

无论如何,除非你有充分的理由这样做,否则我会避免这种情况。你正在牺牲一个强大的打字系统的优点,无法改进。

当然使用反射的充分理由,但在这种情况下我没有看到优点。

您可以通过字符串插值连接名称

var concatenated = $"{names.Name1}{names.Name2}{names.Name3}{names.Name4}{names.Name5}";

优点是,该解决方案可以进行编译器时间类型检查。如果拼错了其中一个属性,您将获得即时反馈,而不是您可能需要调试的运行时错误。

此外,这种解决方案更加清晰,并且不需要读者超出必要的思考。 (Code is read much more often than it is written, so plan accordingly

但是如果你必须以这种方式编写代码来实现你想要的东西,你应该开始考虑你的设计。什么是问题域,证明Names类,特别是连接的合理性?

答案 1 :(得分:2)

试试这个:

        string varName= names// object to return property value
             .GetType() // get the type
             .GetProperty("Name" + i.ToString()) //get the property of type
             .GetValue(names); // get the value of property in object

函数GetType返回对象类型。 函数GetProperty返回属性类型 函数GetValue返回属性un object

的值

答案 2 :(得分:0)

属性不是为此而设计的。使用列表,例如:

class Names
{
   public List<string> NamesList { get; set; }
}

       ...

for (int i = 1; i <= 5; i++)
{
    var result += NamesList[i];
    ...
}

答案 3 :(得分:-2)

string concatedstr=String. Empty ;

for (int i = 1; i <= 5; i++) {

    string varName = "Name";
    Type t = typeof(Car); 
    PropertyInfo prop = t.GetProperty(varName + i.ToString()); 
    if (null != prop) 
        concatedstr+= prop.GetValue(this, null);
    }
}