繁体   English   中英

在C#中强制转换为未知类型的反射

[英]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);
}

如果您尝试调用用户定义的转换(例如,从XElementString ), 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.

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