简体   繁体   中英

Activator.CreateInstance needs another object to be instantiated

I am instantiating my objects with the classical

object myObject = Activator.CreateInstance(myType);

code and if works fine. The thing is that, now, Id like to instantiate an object and in its constructor, there is a reference to another object. So if I just do the code above, I got a NullReferenceException exception :

Object reference not set to an instance of an object.

I tried to instantiate the concerned object (with Activator.CreateInstance) but I got the same exception... I feel like instantiating the problematic object before my 2nd CreateInstance call is not enough. What should I do ?

EDIT : here's the code of the problem

//A regionManager in needed by MainView as far as I understand the Exception's details
var regionManager = Assembly.LoadFrom("RegionView.dll");
Type rmType = regionManager.GetType("Framework.Hmi.RegionManager");
object obj = Activator.CreateInstance(rmType);
//This works !

var shellViewLibrary = Assembly.LoadFrom("ShellView.dll");
Type svType = shellViewLibrary.GetType("Framework.ShellView.MainView");
object objjj = Activator.CreateInstance(svType);

The last line fails and the error is a NullReferenceException with the details :

at Hmi.RegionManager.get_RegionFactory()
at Hmi.RegionManager.CreateRegion(DependencyObject element)
at Hmi.RegionManager.OnSetRegionNameCallback(DependencyObject element, DependencyPropertyChangedEventArgs args)
at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
[...]

I call c/c the 30/40 other error lines but I don't think it is that usefull...

When you say your constructor references another object, do you mean you should be passing it to the constructor as a parameter? If so, then there is an overload for Activator.CreateInstance that allows you to specify the parameter values. See MSDN for details, but basically, you add them after the type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM