我有一个对象,其属性为ct1-ct5。该对象是自动生成的linq-to-sql对象。我想在c#中为这些属性分配值。有什么办法可以在for循环中做到这一点吗?
例如类似(对象名称:new_condition):
for (int i = 1; tag <= 5; i++)
{
new_condition.cti = values[i];
}
其中,i
在CTI得到评估。
提前致谢
您可以使用反射来完成。例如,假设您有一个A
像这样的类:
class A
{
public int P1 { get; set; }
public int P2 { get; set; }
public int P3 { get; set; }
}
您可以像以下简单的控制台示例中那样进行操作:
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();
}
输出将是:
P1 = 1
P2 = 2
P3 = 3
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句