lundi 23 février 2015

on constructing the class, i want to dynamically intialize all the ISet with HashSet,


Below is how I achieved it for for IList with List



var properties = GetType()
.GetProperties()
.Where(x => x.PropertyType.IsGenericType &&
x.PropertyType.GetGenericTypeDefinition() == typeof(IList<>))
.ToList();

foreach (var property in properties)
{
// get T type of ISet
if (property.PropertyType.GetGenericArguments().Length > 1) continue;
var listElemType = property.PropertyType.GetGenericArguments()[0];
if (listElemType == null) continue;

// create hashedset
var constructorInfo = typeof(List<>)
.MakeGenericType(listElemType)
.GetConstructor(Type.EmptyTypes);

//construct object
if (constructorInfo == null) continue;
var listInstance = (IList)constructorInfo.Invoke(null);
property.SetValue(this, listInstance);
}


but if I try the same thing for ISet, it does not work :(



var properties = GetType()
.GetProperties()
.Where(x => x.PropertyType.IsGenericType &&
x.PropertyType.GetGenericTypeDefinition() == typeof(ISet<>))
.ToList();

foreach (var property in properties)
{
// get T type of ISet
if (property.PropertyType.GetGenericArguments().Length > 1) continue;
var listElemType = property.PropertyType.GetGenericArguments()[0];
if (listElemType == null) continue;

// create hashedset
var constructorInfo = typeof(HashSet<>)
.MakeGenericType(listElemType)
.GetConstructor(Type.EmptyTypes);

//construct object
if (constructorInfo == null) continue;
//============== HERE IS THE PROBLEM ============
// var listInstance = (ISet)constructorInfo.Invoke(null);
// property.SetValue(this, listInstance);
}


there is no ISet like for IList.. how to achieve it in this case??






Aucun commentaire:

Enregistrer un commentaire