Пример #1
0
        public TNewClass CastAsClass <TNewClass>() where TNewClass : class
        {
            if (_classOptions.IsStrict &&
                !ClassHelper.AreClassesRelated <TExistingClass, TNewClass>())
            {
                throw new CastingException("Only related classes can be cast where option strict is set");
            }

            var newObject = Activator.CreateInstance <TNewClass>();
            var newProps  = typeof(TNewClass).GetProperties();

            foreach (var prop in newProps)
            {
                if (!prop.CanWrite)
                {
                    continue;
                }

                var existingPropertyInfo = typeof(TExistingClass).GetProperty(prop.Name);
                if (existingPropertyInfo == null || !existingPropertyInfo.CanRead)
                {
                    continue;
                }
                var value = existingPropertyInfo.GetValue(_existingClass);

                prop.SetValue(newObject, value, null);
            }

            return(newObject);
        }