C#反射。目标异常未得到处理

时间:2012-05-02 07:22:37

标签: c# exception reflection

NetworkElementCountersFactory factory=new NetworkElementCountersFactory();
List<NetworkElementCounters> neCountersList= new List<NetworkElementCounters>();
NetworkElementCounters neCounters;
while (reader.Read())
{
    i = 4;
    neCounters = factory.getInstance(tableName, reader.GetInt32(0), reader.GetDateTime(1), reader.GetDateTime(2), reader.GetInt32(3));
    foreach (var v in neCounters.Fields)
    {
        v.GetType().GetProperty("CounterValue").SetValue(neCounters.GetType(), reader.GetValue(i), null);
        i++;
    }
    neCountersList.Add(neCounters);
} 

我在这里收到例外:

v.GetType().GetProperty("CounterValue").SetValue(neCounters.GetType(), reader.GetValue(i), null);

1 个答案:

答案 0 :(得分:3)

这看起来非常错误:

.SetValue(neCounters.GetType(), {whatever}, null);

这意味着您正尝试在Type实例上进行分配。您应该在此处传递目标对象,或null如果它是static属性。 看起来就像这样:

.SetValue(neCounters, {whatever}, null);

然后它会更容易使用:

neCounters.CounterValue = ...
// v.CounterValue = ... // <=== might be this instead - confusing context
如果这里存在一些复杂性,可能会通过dynamic

dynamic obj = neCounters;
// dynamic obj = v; // <=== might be this instead - confusing context
obj.CounterValue = reader.GetValue(i);