![](/img/trans.png)
[英]Setting the value of a static field using Reflection.Emit fails in Unity
[英]using LINQ and reflection to get static readonly field values fails
我正在使用像這樣的反射獲取一些靜態只讀字段值
FieldInfo[] allUnits =
new Unit().GetType().GetFields(BindingFlags.Static | BindingFlags.Public);
然后我成功獲得了一個像這樣的單個字段值
Unit v = (Unit)allUnits[0].GetValue(null);
Console.WriteLine(v.Symbol.StartsWith("e"));
並且還會打印“ True”。那么為什么此LINQ查詢要獲取多個類似的字段值,例如...
IEnumerable<FieldInfo> fis2 =
from fi in allUnits
where ((Unit)fi.GetValue(null)).Symbol.StartsWith("e")
select fi;
...失敗並產生空結果集?
我得到的異常是System.SystemException: specified cast is not valid
看來由fi.GetValue(null)
返回的值之一的類型實際上不是Unit
類型; 無論如何,使用其他子句(例如fi.FieldType == typeof(Unit)
或類似的東西fi.FieldType == typeof(Unit)
,您都可以安全地檢查類型:
IEnumerable<FieldInfo> fieldInfos =
from field in fields
where field.FieldType == typeof(Unit) &&
((Unit)field.GetValue(null)).Symbol.StartsWith("e")
select field;
格蘭特的解決方案也可以寫成
IEnumerable<FieldInfo> fieldInfos = fields
.Select(f => f.GetValue(null))
.OfType<Unit>()
.Where(u => u.Symbol.StartsWith("e"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.