动态地为对象属性赋值

bob*_*bob 3 .net c#

我有一个属性为 ct1 - ct5 的对象。该对象是一个自动生成的 linq-to-sql 对象。我想在 c# 中为这些属性赋值。有没有办法在 for 循环中做到这一点?

例如类似(对象名称:new_condition):

for (int i = 1; tag <= 5; i++)
{
   new_condition.cti = values[i];
}
Run Code Online (Sandbox Code Playgroud)

其中,i在CTI得到评估。

提前致谢

Raú*_*año 6

您可以使用反射来做到这一点。例如,假设你有一个A这样的类:

class A
{
    public int P1 { get; set; }
    public int P2 { get; set; }
    public int P3 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

你可以像在这个简单的控制台示例中那样做:

static void Main(string[] args)
{
    var a = new A();
    foreach (var i in Enumerable.Range(1,3))
    {
        a.GetType().GetProperty("P" + i).SetValue(a, i, null);
    }
    Console.WriteLine("P1 = {0}",a.P1);
    Console.WriteLine("P2 = {0}",a.P2);
    Console.WriteLine("P3 = {0}",a.P3);
    Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)

输出将是:

P1 = 1
P2 = 2
P3 = 3
Run Code Online (Sandbox Code Playgroud)