Подтвердить что ты не робот

С# Создание неизвестного типа общего типа во время выполнения

Итак, у меня есть класс, который является общим, и ему может понадобиться, внутри своего метода, создать собственный экземпляр с другим родовым типом, который будет получен через проверку.

Это важно, потому что этот репозиторий сопоставляет T с таблицей базы данных [это ORMish, которую я пишу], и если класс, представляющий T, имеет коллекцию, представляющую таблицу ANOTHER, мне нужно иметь возможность указать этот экземпляр и передать его в репозиторий [ala Inception].
Я предоставляю этот метод на случай, если вам будет легче увидеть проблему.

    private PropertiesAttributesAndRelatedClasses GetPropertyAndAttributesCollection()
       {
     // Returns a List of PropertyAndAttributes
     var type = typeof(T); 
//For type T return an array of PropertyInfo

     PropertiesAttributesAndRelatedClasses PAA = new PropertiesAttributesAndRelatedClasses(); 
//Get our container ready

         PropertyAndAttributes _paa;
         foreach (PropertyInfo Property in type.GetProperties())
 //Let loop through all the properties.

           {                    
         _paa = new PropertyAndAttributes();
 //Create a new instance each time.

        _paa.AddProperty(Property);
 //Adds the property and generates an internal collection of attributes for it too

        bool MapPropertyAndAttribute = true;
        if (Property.PropertyType.Namespace == "System.Collections.Generic")
    //This is a class we need to map to another table
               {
                   PAA.AddRelatedClass(Property);
                 //var x = Activator.CreateInstance("GenericRepository", Property.GetType().ToString());
                    }
                    else
                    {
                      foreach (var attr in _paa.Attrs)
                        {
                          if (attr is IgnoreProperty)
 //If we find this attribute it is an override and we ignore this property.
                            {
                               MapPropertyAndAttribute = false;
                               break;
                            }
                        }
                    }
                    if (MapPropertyAndAttribute)
                      PAA.AddPaa(_paa);
            //Add this to the list.
                }
                return PAA;
            }

Итак, данный GenericRepository, и я хочу создать GenericRepository, как бы это сделать? Строка, которую мне нужно заменить чем-то, что РАБОТАЕТ

//                    var x = Activator.CreateInstance("GenericRepository", Property.GetType().ToString());
4b9b3361

Ответ 1

Я думаю, что вы ищете метод MakeGenericType:

// Assuming that Property.PropertyType is something like List<T>
Type elementType = Property.PropertyType.GetGenericArguments()[0];
Type repositoryType = typeof(GenericRepository<>).MakeGenericType(elementType);
var repository = Activator.CreateInstance(repositoryType);

Ответ 2

Activator.CreateInstance(typeof(GenericRepository<>).MakeGenericType(new Type[] { Property.GetTYpe() }))