User-defined conversion operator from base class

前端 未结 11 1561
南旧
南旧 2020-12-01 02:40

Introduction

I am aware that \"user-defined conversions to or from a base class are not allowed\". MSDN gives, as an explanation to this rule, \"You

11条回答
  •  渐次进展
    2020-12-01 02:57

    Ugg, I ended up just doing a simple Cast() method inside my modified entity. Maybe I am just missing the point, but I need to modify my base type so I can keep my code inside the new object to do x. I would have used public static explicit operator if the compiler would let me. The inheritance messes it up explicit cast operator.

    Usage:

    var newItem = UpgradedEnity(dbItem);
    var stuff = newItem.Get();
    

    Sample:

    public class UpgradedEnity : OriginalEnity_Type
        {
            public string Get()
            {
                foreach (var item in this.RecArray)
                {
                    //do something
                }
                return "return something";
            }
    
            public static UpgradedEnity Cast(OriginalEnity_Type v)
            {
                var rv = new UpgradedEnity();
                PropertyCopier.Copy(v, rv);
                return rv;
            }
    
            public class PropertyCopier where TParent : class
                                                where TChild : class
            {
                public static void Copy(TParent from, TChild to)
                {
                    var parentProperties = from.GetType().GetProperties();
                    var childProperties = to.GetType().GetProperties();
    
                    foreach (var parentProperty in parentProperties)
                    {
                        foreach (var childProperty in childProperties)
                        {
                            if (parentProperty.Name == childProperty.Name && parentProperty.PropertyType == childProperty.PropertyType)
                            {
                                childProperty.SetValue(to, parentProperty.GetValue(from));
                                break;
                            }
                        }
                    }
                }
            }
        }
    

提交回复
热议问题