türünün kısıtlamasını ihlal ediyor, bu yüzden bir süre saçımı dışarı çekiyorum, aslında şu şekilde çağrılan genel bir depo fabrikası uygulamaya çalışıyorum:Generics & Reflection - GenericArguments [0],
public class RepositoryFactory<T> : IRepositoryFactory<T>
{
public T GetRepository(Guid listGuid,
IEnumerable<FieldToEntityPropertyMapper> fieldMappings)
{
Assembly callingAssembly = Assembly.GetExecutingAssembly();
Type[] typesInThisAssembly = callingAssembly.GetTypes();
Type genericBase = typeof (T).GetGenericTypeDefinition();
Type tempType = (
from type in typesInThisAssembly
from intface in type.GetInterfaces()
where intface.IsGenericType
where intface.GetGenericTypeDefinition() == genericBase
where type.GetConstructor(Type.EmptyTypes) != null
select type)
.FirstOrDefault();
if (tempType != null)
{
Type newType = tempType.MakeGenericType(typeof(T));
ConstructorInfo[] c = newType.GetConstructors();
return (T)c[0].Invoke(new object[] { listGuid, fieldMappings });
}
}
}
Ben GetRespository aramaya çalıştığımda
aşağıdaki satırıType newType = tempType.MakeGenericType(typeof(T));
başarısız işlev:
var resposFactory = new RepositoryFactory<IRepository<Document>>();
depo fabrika aşağıdaki gibi görünür
I elde hatadır:
ArgumentException - GenericArguments [0] 'Framework.Repositories.IRepository`1 [Apps.Documents.Entities.PerpetualDocument]', Framework.Repositories.DocumentLibraryRepository`1' ile [T] 'T' türünün kısıtlamasını ihlal ediyor.
Burada yanlış olanlarla ilgili herhangi bir fikir var mı?
DÜZENLEME: Aşağıdaki
depo uygulanması gibi:
public class DocumentLibraryRepository<T> : IRepository<T>
where T : class, new()
{
public DocumentLibraryRepository(Guid listGuid, IEnumerable<IFieldToEntityPropertyMapper> fieldMappings)
{
...
}
...
}
Ve benzeri IRepository görünür:
public interface IRepository<T> where T : class
{
void Add(T entity);
void Remove(T entity);
void Update(T entity);
T FindById(int entityId);
IEnumerable<T> Find(string camlQuery);
IEnumerable<T> All();
}
Orada bir iade bildirimi eksik misiniz? Bu yöntemin tam bir kopyasını mı yapıştırdınız? –
Ayrıca, bir kurucu parametrelerini açıkça çağırmak istediğinizde neden parametresiz bir kurucunun varlığını kontrol ediyorsunuz? Eğer parametresiz bir kurucunuz varsa, büyük olasılıkla 'GetConstructors' tarafından döndürülen 0 kurucu olacaktır, bu durumda * ile * parametreleri başarısız olacaktır. –
Evet özür dileriz 'dönüş varsayılanı (T)' en sonunda olmalıdır. – Bevan