简体   繁体   English

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

[英]C# reflection. Target exception was unhandled

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);
} 

I receive the exception here: 我在这里收到异常:

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

This looks very wrong: 这看起来很错误:

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

That means you are trying to assign this on a Type instance. 这意味着您正在尝试在Type实例上分配它。 You should be passing the target object here, or null if it is a static property. 您应该在此处传递目标对象;如果它是static属性,则为null It looks like this should be: 看起来应该是这样的:

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

but then it would be easier to use: 但是使用起来会更容易:

neCounters.CounterValue = ...
// v.CounterValue = ... // <=== might be this instead - confusing context

maybe via dynamic if there is some complexity here: 如果这里有些复杂,也许可以通过dynamic

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM