Permanently cast derived class to base

前端 未结 6 1550
慢半拍i
慢半拍i 2020-12-09 16:19
Class A { }
Class B : A { }

B ItemB = new B();
A ItemA = (A)B;

Console.WriteLine(ItemA.GetType().FullName);

Is it possible to do something like a

6条回答
  •  轮回少年
    2020-12-09 16:53

    I've recently run into this migrating an old project to Entity Framework. As it was mentioned, if you have a derived type from an entity, you can't store it, only the base type. The solution was an extension method with reflection.

        public static T ForceType(this object o)
        {
            T res;
            res = Activator.CreateInstance();
    
            Type x = o.GetType();
            Type y = res.GetType();
    
            foreach (var destinationProp in y.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
            {
                var sourceProp = x.GetProperty(destinationProp.Name);
                if (sourceProp != null)
                {
                    destinationProp.SetValue(res, sourceProp.GetValue(o));
                }
            }
    
            return res;
        }
    

    It's not too neat, so use this if you really have no other option.

提交回复
热议问题