system.reflection - Conditionally instantiate a class in C# -



system.reflection - Conditionally instantiate a class in C# -

i've been busting hump trying new code work. have been able in simpler more extensive way, through if statements. however, going version 2 of application, code little cleaner , more efficient.

what trying conditionally instantiate class. go this:

int aeroplane = 195; if (airplane == 190) _e190 aircraft = new _e190(); else if (airplane == 195) _e195 aircraft = new _e195();

i have both classes, utilize keyword "aircraft" don't have create multiple parts of code each class. have found out multiple inheritance (which, in opinion, trick) not available in c#, , relatively new language.

so far, have accomplished instantiate class way want, can't seem utilize variables declared within each class. have done this:

int aeroplane = 195; var aircraft = activator.createinstance( (airplane == 195) ? typeof(_e195) : typeof(_e190)); messagebox.show(aircraft.gettype().tostring());

the messagebox shows type correctly, again, can't access class using "aircraft" object. there more ways this, of them fine me.

thanks!

i take they're each inherited else , that's why need multiple inheritance?

make interface (iaircraft) , have them both implement it.

interface iaircraft { /* mutual methods here */ } class _e190 : theparentclass, iaircraft { /* code */ } class _e195 : theotherparentclass, iaircraft { /* code */ } /* ... */ int aeroplane = 195; iaircraft aircraft; if (airplane == 190) aircraft = new _e190(); else if (airplane == 195) aircraft = new _e195();

the reason can't access class using previous method because that, compiler needs know type of class is. , that, you'd need cast appropriate type... brings right same problem. utilize reflection methods go on that, it's much more efficient , clean utilize inheritance or implementation.

c# system.reflection

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

c# - Can ProtoBuf-Net deserialize to a flat class? -

javascript - Change element in each JQuery tab to dynamically generated colors -