Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is an alternative to having static abstract methods?
    text
    copied!<p>I'm having some problems trying to figure out how to solve a problem without being able to have static method in an abstract class or interface. Consider the following code. I have many Wizards that inherit from AbsWizard. Each wizard has a method GetMagic(string spell) that only returns magic for certain magic words, yet all instances of a specific type of wizard respond to the same set of magic words.</p> <pre><code>public abstract class AbsWizard { public abstract Magic GetMagic(String magicword); public abstract string[] GetAvalibleSpells(); } public class WhiteWizard : AbsWizard { public override Magic GetMagic(string magicword) { //returns some magic based on the magic word } public override string[] GetAvalibleSpells() { string[] spells = {"booblah","zoombar"}; return spells; } } public class BlackWizard : AbsWizard { public override Magic GetMagic(string magicword) { //returns some magic based on the magic word } public override string[] GetAvalibleSpells() { string[] spells = { "zoogle", "xclondon" }; return spells; } } </code></pre> <p>I want the user to be able to first choose the type of wizard, and then be presented with a list of the spells that type of wizard can cast. Then when they choose a spell the program will find all, if any, existing wizards of the selected type and have them cast the selected spell. All wizards of a specific type will always have the same available spells, and I need a way to determine the spells a specific type of wizard can cast with out actually having access to an instance of the selected type of wizard.</p> <p>In addition I don't want to have to depend on a separate list of possible wizard types or spells. Instead I would rather just infer everything through GetAvalibleSpells() and reflection. For example I plan to cast magic as follows:</p> <pre><code> public static void CastMagic() { Type[] types = System.Reflection.Assembly.GetExecutingAssembly().GetTypes(); List&lt;Type&gt; wizardTypes = new List&lt;Type&gt;(); List&lt;string&gt; avalibleSpells = new List&lt;string&gt;(); Type selectedWizardType; string selectedSpell; foreach (Type t in types) { if (typeof(AbsWizard).IsAssignableFrom(t)) { wizardTypes.Add(t); } } //Allow user to pick a wizard type (assign a value to selectedWizardType) //find the spells the selected type of wizard can cast (populate availibleSpells) //Alow user to pick the spell (assign a value to selectedSpell) //Find all instances, if any exsist, of wizards of type selectedWizardType and call GetMagic(selectedSpell); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload