foreach (PropertyInfo pi in t.GetProperties(bf))
{      
    //把控件属性Text的值赋给entity    
       pi.SetValue(entity, s,null);     
}我想把传过来的字符串 赋给entity 的属性 pi,但是entity的属性类型不一样,所以我想把s 动态转型为 pi.PropertyType,
但是我这样写(pi.PropertyType)s ,编译不了的..Net里面转型操作的时候,是不是一定要类型确定了才能转型?这个在.net里面是不是不能实现?如果遇到这种操作,难道只能用现有的类型去判断?

解决方案 »

  1.   

    你说你要求c#能够把string转换为任意的“entity的属性类型”,如果c#真的如此操作而不出现编译错误,c#也就是个不可预测的乱东西了。
      

  2.   

    我来学习,只知道在 oracle 有个 %TYPE,C#不知道怎么用。顺便想接点分,嘿嘿~~~
      

  3.   


    switch case
    手工转换吧.
      

  4.   

    编译通不过应该是正常的,因为编译器不知道 pi.PropertyType是个什么东西看能不能重载操作符来完成不过,有想法就有需求.
      

  5.   

    Type tmp = pi.PropertyType;if (tmp == typeof(int))
                            {
                                pi.SetValue(entity, Int32.Parse(textinfo.GetValue(controls[pi.Name], null).ToString()), null);
                            }
                            if (tmp == typeof(string))
                            {
                                pi.SetValue(entity, (string)textinfo.GetValue(controls[pi.Name], null), null);
                            }                        目前我只能用这种办法,但是当出现一个新类型时,我就要手动添加一个,麻烦.
      

  6.   

    OO 看多了, 看到 if else 就想消除.要求有点过分了,呵呵!
      

  7.   

    private T SetPropertyValue(PropertyInfo entitypi,ref T entity,PropertyInfo controlpi,object control)
            {
                if (entitypi.PropertyType == typeof(int))
                {
                    entitypi.SetValue(entity, Int32.Parse(controlpi.GetValue(control, null).ToString()), null);
                }
                if (entitypi.PropertyType == typeof(string))
                {
                    entitypi.SetValue(entity, (string)controlpi.GetValue(control, null), null);
                }
                if (entitypi.PropertyType == typeof(float))
                {
                    entitypi.SetValue(entity, Single.Parse(controlpi.GetValue(control, null).ToString()), null);
                }
                if (entitypi.PropertyType == typeof(DateTime))
                {
                    entitypi.SetValue(entity, DateTime.Parse(controlpi.GetValue(control, null).ToString()), null);
                }            return entity;
            }最后也只能把这个 封装成一个函数了,要改也只改一个地方,最好能作到这样了.