代码之家  ›  专栏  ›  技术社区  ›  Dan Monego

getDefinitionByName中的奇怪行为

  •  0
  • Dan Monego  · 技术社区  · 17 年前

    我创建了一个类,该类根据传递给它的名称加载它的子类。函数使用getDefinitionByName,获取类类型并实例化它,如果类是拥有此方法的类的子类型,则返回它。子类型都是扩展基类的mxml文件,以简化实例化控件。

    但是,如果我向它传递一个完全限定的名称,它在我的单元测试中工作,但在我的应用程序上下文中执行时失败。getDefinitionByName中是否存在使其在不同执行上下文中表现不同的问题?有没有一种更简单的方法来按类的限定名加载类?

    static public function loadDisplay(className:String, extendedClassName:String = null):FeatureDisplay
    {
        try
        {
            trace("Loading", className);
            var cls:Class = getDefinitionByName(className) as Class;
            var display:FeatureDisplay = new cls() as FeatureDisplay;
            if(display)
            {
                return display;
            }
            else
            {
                trace(className, "is not a subclass of FeatureDisplay");
                return null;
            }
        }
        catch(error:Error)
        {
            trace("Error loading", className);
            trace("Error:", error.message);
        }
        return null;
    }
    
    2 回复  |  直到 17 年前
        1
  •  3
  •   cwallenpoole    17 年前

    我的第一个问题是你在吗 明确地 在任何地方使用任何类?如果您没有实际使用某个类,即使该类已导入,ActionScript也可能不会在swf中保留该类定义的副本。

    也就是说,如果可以避免的话,最好避免使用getDefinitionByName、DescripteType、getQualifiedClassName或getQualifiedSuperclassName。他们是内存消耗者,通常最好避免他们。(除非您无法控制在运行时使用哪些类,并且

    我的建议是用swtich…case替换getQualifiedClassName:

    // Import the subclasses.
    import path.to.SpriteFeatureDisplay;
    import path.to.OtherFeatureDisplay;
    
    class FeatureDisplay extends Sprite{
    
       //Make one public static const per class.
       public static const SPRITE_FEATURE_DISPLAY:String = "sprite_feature_display";
       public static const OTHER_FEATURE_DISPLAY:String  = "other_feature_display";
    
       public static function loadDisplay(  className:String, 
                                            extName:String = null ):FeatureDisplay
       {
          trace("Loading", className);
    
          // This will ensure that each of the classes is stored in the swf
          // it will behave faster, and it is less prone to errors (note that 
          // try...catch is not needed).
          swtich( className )
          {
              case SPRITE_FEATURE_DISPLAY:
                return new SpriteFeatureDisplay();
              case OTHER_FEATURE_DISPLAY:
                return new OtherFeatureDisplay();
              default:
                trace( "Requested class " + className + " could not be created..." +
                "\nPlease make sure that it is a subclass of FeatureDisplay" );
                return null;
          }
          return null;
       }
    }
    
        2
  •  2
  •   Richard Szalay    17 年前

    仅供参考,我见过以下在Flex源代码中保留类的方法:

    // References.cs
    
    // notice the double reference: one to import, the other to reference
    import package.to.ClassA; ClassA;
    import package.to.ClassB; ClassB;
    import package.to.ClassC; ClassC;