2009-11-21 17 views
5

mi problema en pocas palabras:C#: La herencia de los miembros estáticos separados para las clases derivadas

class A 
{ 
    /* Other stuff in my class*/ 
    protected static staticMember; 
} 

class B : A 
{ 
    /* Other stuff in my class*/ 
    // Will have A.staticMember but I want B.staticMember (same type) 
} 

class C : A 
{ 
    /* Other stuff in my class*/ 
    // Will have A.staticMember but I want C.staticMember (same type) 
} 

Así que quiero toda mi clase derivada de tener un datos compartidos que se comparte para esa clase paricular pero tienen una firma común definido en la clase base.

Estoy creando un juego de estrategia en tiempo real simple para divertirme en mi tiempo libre. Hay varios tipos de unidades (naves espaciales, edificios, etc.) que tienen algunos atributos básicos. Estas unidades pueden ser actualizados por los jugadores (todas las unidades del mismo tipo que pertenezcan al mismo jugador se actualizan por ejemplo. El jugador A mejoras en el blindaje de los tanques significa que todos sus tanques tendrán mejor armadura.)

Aquí es cómo me trató a achive esto:

abstract class Unit 
{ 
    /*several methods that is common for all units*/ 

    /*We don't know the unit's attributes at this point*/ 
    protected abstract double getMaxHitpoints(); 
    protected abstract double getFusionArmor(); 
    protected abstract double getNormalArmor(); 
    // and more similar abstract methods to come. 

    double maxHitpoints; 
    double fusionArmor; 
    double normalArmor; 
    //... 

    // This method is called on construction and after upgrade completion. 
    public void cacheAttributes(Player forPlayer) 
    { 
     Upgrade upgradesForThisUnit; //<<< Upgrade is class that is used like a struct to hold the upgrades for this kind of unit. 
     upgrades.TryGetValue(forPlayer,out upgradesForThisUnit); ///< get upgrades if available (if not available it will give the default value [=no bonuses]) 

     maxHitpoints=getMaxHitpoints()+upgradesForThisUnit.hitpointBonus; 
     fusionArmor=getFusionArmor()+upgradesForThisUnit.fusionArmorBonus; 
     normalArmor=getNormalArmor()+upgradesForThisUnit.normalArmorBonus; 
     //... 
    } 
    // This data structure is intended to hold the upgrades for every player for this kind of the unit 
    // but unfortunally derived classes have this instance too so if the player upgrades the tanks it will upgrade the interceptors, peasants, buildings too... 

    protected static Dictionary<Player,Upgrade> upgrades; 
} 

class Tank : Unit 
{ 
    protected override double getMaxHitpoints() {return 1000;} 
    protected override double getFusionArmor() {return 10;} 
    protected override double getNormalArmor() {return 50;} 
    //... 
} 

I pensado en añadir una tecla adicional a mi Dictonary (utilizando el diccionario anidada): estructuras de tipo como clave y modificar el código como el siguiente:

protected static Dictionary<Player,Dictionary<Type,Upgrade>> upgrades; 

public void cacheAttributes(Player forPlayer) 
{ 
    Dictionary<Type,Upgrade> upgradesForThePlayer; 
    upgrades.TryGetValue(forPlayer,out upgradesForThePlayer); 

    Upgrade upgradesForThisUnit; //<<< Upgrade is class that is used like a struct to hold the upgrades for this kind of unit. 
    upgradesForThePlayer.TryGetValue(GetType(),out upgradesForThisUnit); ///< get upgrades if available (if not available it will give the default value [=no bonuses]) 

    maxHitpoints=getMaxHitpoints()+upgradesForThisUnit.hitpointBonus; 
    fusionArmor=getFusionArmor()+upgradesForThisUnit.fusionArmorBonus; 
    normalArmor=getNormalArmor()+upgradesForThisUnit.normalArmorBonus; 
    //... 
} 

Pero ' No estoy seguro de que esto funcione como se esperaba.

La solución es probablemente simple pero no tengo ni idea de cómo resolver esto ahora.

Respuesta

0

Si por un diccionario de diccionarios quiere decir algo aproximadamente como Dictionary<Player, Dictionary<Type, Upgrade>> entonces, sí, funcionará como espera y es una buena solución para el problema tal como se establece. También puedes usar una matriz de Diccionarios si tienes un número pequeño de reproductores máximos, realmente no estás obteniendo nada demasiado útil como hash 4 valores. (Si usted tiene un máximo de 4 jugadores)

1
public class Singleton<T> 
    { 
     private static string _value; 
     public string Value 
     { 
      get 
      { 
       return _value; 
      } 
      set 
      { 
       _value = value; 
      } 
     } 
    } 
    public class At<T> 
    { 
     public static Singleton<T> field = new Singleton<T>(); 
    } 

    public class Bt : At<Bt> 
    { 
    } 

    public class Ct : At<Ct> 
    { 
    } 
... 
    Bt.field.Value = "bt"; 
    Ct.field.Value = "ct"; 
0

Una bastante antigua pregunta, pero, en beneficio del pueblo del futuro, así es como llegué en torno a un problema similar.

class A 
{ 
    /* Other stuff in my class*/ 
    protected MyClass nonStaticMember; 
} 

class B : A 
{ 
    private static B _instance; 
    public static B instance 
    { 
     get 
     { 
      return _instance; 
     } 
    } 
    static B() 
    { 
     _instance = new B(); 
    } 
    /* Other stuff in my class*/ 
    // Will have B.instance.nonStaticMember 
} 

class C : A 
{ 
    private static C _instance; 
    public static C instance 
    { 
     get 
     { 
      return _instance; 
     } 
    } 
    static C() 
    { 
     _instance = new C(); 
    } 
    /* Other stuff in my class*/ 
    // Will have C.instance.nonStaticMember 
} 

Esto supone que es posible que desee acceder C.instance.doSomethingTo_nonStaticMember() de otra clase.

Cuestiones relacionadas