Generic类中的GetProperty返回null

时间:2016-05-16 12:37:25

标签: c# generics

在我正在工作的项目中有一个如下定义的类:

var mediaBlockRenderer = function(block) {
    if (block.getType() === 'atomic') {
        return {
            component: TestComponent,
            editable: false
        };
    }
    return null;
};

var TestComponent = function() {
    return <div className="test-component">TEST COMPONENT</div>;
};

onChange: function(editorState) {
        var currentKey = editorState.getSelection().getStartKey();
        var content = editorState.getCurrentContent();
        var selection = content.getSelectionBefore();
        var beforeKey = content.getKeyBefore(currentKey);
        var block = content.getBlockForKey(beforeKey);

        if (block && block.getText() === 'test') {
            console.log(block.getText());
            var len = block.getCharacterList().size;

            var newSelection = selection.merge({
                anchorOffset: 0,
                focusOffset: len
            });

            var newContent = Modifier.removeRange(content, newSelection, 'backward');
            editorState = EditorState.push(editorState, newContent, 'insert');
            var key = Entity.create('media', 'IMMUTABLE');
            editorState = AtomicBlockUtils.insertAtomicBlock(
                editorState,
                key,
                ' '
            );
            //editorState = EditorState.forceSelection(editorState, newContent.getSelectionBefore());

        }

        this.setState({
            editorState: editorState
        })
    }

class DataImport<T> : DataBaseClass where T : IDataEntity, new() { } 包含以下字段:

IDataEntity

在实现此接口的类中有以下内容:

string tableName { get; }
string Id { get; }
int TypeId { get;  }

例如。

string IDataEntity.Id { get { return myobject_id.ToString(); } } int IDataEntity.TypeId { get { return 10; } } string IDataEntity.tableName { get { return "tblObjects"; } } 对象中,我想这样做:

DataImport

等。但我当然不能这样做。 我已经尝试将它们宣布为公开但不允许这样做。

如何访问string x = (T).tableName; tableNameId属性?我看过TypeId,但他们是typeof(T).GetProperties();在null也。

1 个答案:

答案 0 :(得分:4)

有两个问题:

  1. 您需要T的实例来访问非静态属性tableName,在您的示例中,您在类型<上调用(T).tableName / em>而不是实例
  2. 由于您的类显式实现了接口(string IDataEntity.tableName),因此您需要明确地将T的实例强制转换为IDataEntity
  3. 因此,您的DataImport实现应该如下所示:

    class DataImport<T> : DataBaseClass where T : IDataEntity, new()
    {
        public void WriteTableName(T arg)
        {
            string x = ((IDataEntity)arg).tableName;
            Console.WriteLine(x);
        }
    }