Как получить Child Generi c? - PullRequest
0 голосов
/ 05 апреля 2020

Я определяю класс BaseController с помощью Generi c Class TEntity.

public class BaseController<TEntity> : Controller 

Использование:

public class ProductController : BaseController<Product>
    {
        public ProductController(BaseService<Product> baseService)
            : base(baseService)
        {

        }

    }

Класс Продукт имеет отношение дочерних свойств. Это динамично c следовать TEntity (класс Product)

public partial class Product
    {

        [Key]
        public long CodeId { get; set; }



        public int Name { get; set; }

        //Config Ref
        [NotMapped]
        public ICollection<ProductDetail> ProductDetails { get; set; }
    }

public partial class ProductDetail
        {

            [Key]
            public long CodeId { get; set; }



            public int Name { get; set; }


        }

TEntity теперь является Product. И я получаю свойство ProductDetails.

var tEn = JsonUtilities.ConvertObjectToObject<TEntity>(obj);    

    var propsInfo = (typeof(TEntity)).GetProperties();

    var propsCollection = propsInfo.Where(x => x.PropertyType.IsGenericType
        && x.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>));


    foreach (var prop in propsCollection)
    {
        dynamic childItems = prop.GetValue(tEn);

        var genericType = prop.PropertyType.GenericTypeArguments[0];
        var tableProp = context.GetType().GetProperties().FirstOrDefault(x => x.Name == genericType.Name);

        foreach (dynamic itemChild in childItems)
        {
            // Convert here for setting some property value
            var dy = JsonUtilities.ConvertObjectToObject<dynamic>(itemChild);

            foreach (KeyValuePair<string, string> itemKey in dic)
            {
                itemChild[itemKey.Value.Trim()] = "DATA" ;  << dynamic property
            }

            // QUESTION HERE
            var itemChild2 =  JsonUtilities.ConvertObjectToObject<ABC???>(dy);  <<<<< 

        } 
    }

Теперь, как я могу снова преобразовать generi c itemChild с объектом класса ProductDetail

var dy = JsonUtilities.ConvertObjectToObject<ProductDetail>(itemChild);  <<< I can not put ProductDetail here because, It's child of generic object Product.

У меня TEntity - Product, а в Product - ProductDetails - CHILD. (Я использовал название Product & ProductDetail для вашего удобства.)

Теперь, у меня TEntity - Продукт. Я могу получить Child Instant of Class ProductDetail. возможно, вызовите 'childClass'. После этого я конвертирую 'childClass' в динамический c объект. Мой вопрос: как снова преобразовать в 'childClass' из динамического c Object.

Ответы [ 2 ]

0 голосов
/ 06 апреля 2020

Вам нужно использовать Interface. Каждый тип, который может использоваться в таком сценарии (например, ProductDetail), должен реализовывать этот интерфейс. В этом случае нет необходимости в нескольких преобразованиях.
Я повторил это.

namespace Project
{
    class Product
    {
        public int Id {get;set;}
        public string Name {get;set;}
        public ICollection<ProductDetail> ProductDetails {get;set;}
    }

    class ProductDetail : IInjectable
    {
        public int Key {get;set;}
        public string Value {get;set;}
    }

    interface IInjectable
    {
        int Key {get;set;}
        string Value {get;set;}
    }

    class Worker
    {
        void Do<TEntity>(TEntity entity, Dictionary<int, string> dic)
        {
            typeof(TEntity)
                .GetProperties()
                .Where(p => p.PropertyType.IsGenericType &&
                            typeof(IEnumerable).IsAssignableFrom(p.PropertyType))
                .Select(p =>
                {
                    var genType = p.PropertyType
                                   .GetGenericArguments()
                                   .FirstOrDefault();
                    return new
                    {
                        Property = p,
                        GenericType = genType,
                    };
                })
                .Where(item => typeof(IInjectable).IsAssignableFrom(item.GenericType))
                .ToList()
                .ForEach(item =>
                {
                    var enumerableValue = item.Property
                                              .GetValue(entity) as IEnumerable;
                    foreach (var v in enumerableValue)
                    {
                        if (v is IInjectable injectable)
                        {
                            injectable.Value = dic[injectable.Key];
                        }
                    }
                });
        }
    }
}
0 голосов
/ 05 апреля 2020

Вы можете вызвать метод generi c с помощью отражения.

                MethodInfo method = typeof(JsonUtilities).GetMethod(nameof(ConvertObjectToObject));
                MethodInfo generic = method.MakeGenericMethod(typeof(prop.PropertyType));
                var itemChild2 = generic.Invoke(this, dy);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...