C # CF2.0 - System.Activator and inner classes

I have a data provider that contains a collection of objects. I only want to create a new object via the data provider.

Ie to create a new entry that I need to use:

Entity entity = Provider.AddNew();
enity.set_Properties... etc

      

My problem is that if I set my entities to Internal, System.Activator fails to instantiate from them. Each of my Data Providers uses a base class with a generic object type passed through.

So, at the moment, my AddNew () method contains the following:

public T AddNew()
{
  T added = Activator.CreateInstance<T>();
  this.Collection.Add(added);
  return added;
}

      

Obviously it's not the end of the world if I can instantiate a new object manually outside of the data provider namespaces, but it seems pointless given that there is no way to save them, so why do that?

EDIT: Forgot to mention that all my providers, entities, etc. are in the same namespace.

0


a source to share


1 answer


Don't use an activator that relies on a public constructor. Instead, use reflection to find the parameterless constructor and then call it. Something like this:



Type t = typeof(MyType);
var parameterlessCtor = (from c in t.GetConstructors(
  BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
    where c.GetParameters().Length == 0
    select c).FirstOrDefault;
if(parameterlessCtor != null) instance = parameterlessCtor.Invoke(null);

      

0


a source







All Articles