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

我在這里收到異常:

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

這看起來很錯誤:

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

這意味着您正在嘗試在Type實例上分配它。 您應該在此處傳遞目標對象;如果它是static屬性,則為null 看起來應該是這樣的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM