[英]casting to an unknown type reflection in C#
我當前遇到的問題是我正在嘗試轉換為未知類型,並且我從以下代碼收到此消息:
找不到類型或名稱空間名稱“ thistype”(您是否缺少using指令或程序集引用?)
String thistype = null;
for (int i = 0; i < items.Length; i++)
{
thistype = typeof(BugManagerQueryOptions).GetProperty(items[i].ToString()).PropertyType.Name;
typeof(BugManagerQueryOptions).GetProperty(items[i].ToString()).SetValue(currentSearch,(thistype)properties[i], null);
}
如果您需要更多信息,請詢問,我們將不勝感激,謝謝。 - 克里斯
假設properties[i]
的值實際上已經是正確的類型,則根本不需要強制轉換:
for (int i = 0; i < items.Length; i++)
{
typeof(BugManagerQueryOptions).GetProperty(items[i].ToString())
.SetValue(currentSearch, properties[i], null);
}
如果您嘗試調用用戶定義的轉換(例如,從XElement
到String
), XElement
復雜得多。
對於將來的參考,這是我嘗試做的(非常草率)的方式,我會對此進行改進,但是我認為我應該把這留給其他人使用。
thistype = typeof(BugManagerQueryOptions).GetProperty(items[i].ToString()).PropertyType.FullName;
if (thistype == "System.String")
{
typeof(BugManagerQueryOptions).GetProperty(items[i]).SetValue(currentSearch, properties[i], null);
}
else if (thistype == "System.Nullable`1[[System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")
{
long number = Int64.Parse(properties[i]);
typeof(BugManagerQueryOptions).GetProperty(items[i]).SetValue(currentSearch, number, null);
}
else if (thistype == "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")
{
int number = Int32.Parse(properties[i]);
typeof(BugManagerQueryOptions).GetProperty(items[i]).SetValue(currentSearch, number, null);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.