我有以下几种类型:

class AddressEditor extends TextEditor {}
class TypeEditor extends TextEditor {}

我试图这样标识编辑器:

void validationErrorHandler( ValidationError e )
{
  var editor = e.editor;
  if( editor is AddressEditor )
   print( editor.runtimeType.toString() ) // prints TextEditor

  if( editor is TypeEditor )
   print( editor.runtimeType.toString() ) // prints TextEditor
}

如果我用镜子

import 'dart:mirrors';

getTypeName(dynamic obj)
{
  return reflect(obj).type.reflectedType.toString();
}

void validationErrorHandler( ValidationError e )
{
  var editor = e.editor;
  if( editor is AddressEditor )
   print( getTypeName( editor ) ) // prints TextEditor

  if( editor is TypeEditor )
   print( getTypeName( editor ) ) // prints TextEditor
}

为什么未识别编辑器类型TypeEditorAddressEditor?是的,我知道这是TextEditor,但是有什么方法可以在Dart中标识TypeEditorAddressEditor

我需要进行这些标识,以使用验证结果。

谢谢

最佳答案

更新

事实证明,TextEditor具有一种newInstance()方法,该方法被调用以通过BWU Datagrid获取新的编辑器实例(基本上TextEditor是一种工厂,并且实现是其中之一)。

因为TypeEditorAddressEditor不会覆盖此方法,所以将创建内部纯TextEditor实例。

为了获得所需的行为,您需要重写newInstance并实现此方法使用的构造函数。由于TextEditor中的构造函数是私有(private)的,因此无法重用并且需要复制(我将重新考虑此设计)。复制的构造函数的前两行需要稍作调整。

然后,AddressEditor看起来像

class AddressEditor extends TextEditor {
  AddressEditor() : super();

  @override
  TextEditor newInstance(EditorArgs args) {
    return new AddressEditor._(args);
  }

  AddressEditor._(EditorArgs args) {
    this.args = args;
    $input = new TextInputElement()
      ..classes.add('editor-text');
    args.container.append($input);
    $input
      ..onKeyDown.listen((KeyboardEvent e) {
      if (e.keyCode == KeyCode.LEFT || e.keyCode == KeyCode.RIGHT) {
        e.stopImmediatePropagation();
      }
    })
      ..focus()
      ..select();
  }
}
TypeEditor是相同的,只是类和构造函数的名称不同。

原始

我非常确定上面带有is的示例可以正常工作,并且问题出在其他地方(这些值不是AddressEditorsTypeEditors,而仅仅是TextEditors

class TextEditor {}

class AddressEditor extends TextEditor {}
class TypeEditor extends TextEditor {}

void main() {
  check(new AddressEditor());
  check(new TypeEditor());
  check(new TextEditor());
}

void check(TextEditor editor) {
  if(editor is AddressEditor) print('AddressEditor: ${editor.runtimeType}');
  if(editor is TypeEditor) print('TypeEditor: ${editor.runtimeType}');
  if(editor is TextEditor) print('TextEditor: ${editor.runtimeType}');
}

输出

AddressEditor: AddressEditor
TextEditor: AddressEditor

TypeEditor: TypeEditor
TextEditor: TypeEditor

TextEditor: TextEditor

关于dart - 如何区分Dart类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25674148/

10-09 06:08