如何在派生类的方法中转换不同的类型?

问题描述 投票:0回答:1

我有一个基类BaseCollectionInspector,它有两个派生类:ReactionCollectionInspectorConditionCollectionInspector

基类有这个方法:

protected override void AddItem(object obj) {
    AssetInfo assetInfo = (AssetInfo) obj;
    string assetName = Path.GetFileNameWithoutExtension(assetInfo.assetPath);
    var assetType = Type.GetType(typeof(BaseReaction).Namespace + "." + assetName + ", Assembly-CSharp");
    var newItem = (BaseReaction) collection.gameObject.AddComponent(assetType);
    newItem.showItem = false; // Hide script in inspector
    int index = collectionList.serializedProperty.arraySize++;

    collectionList.serializedProperty.GetArrayElementAtIndex(index).objectReferenceValue = newItem;
    serializedObject.ApplyModifiedProperties();
}

两个派生类型之间的区别在于,其中一个包含BaseReaction列表和另一个BaseCondition列表,这两个列表都具有showItem属性。

他们都会使用完全相同的AddItem方法,除了在assetTypenewItem上施放。

我正在尝试正确学习C#并且想要使用DRY原则,即使只是复制代码也很容易。我想我可以使用一个接口,但我不确定如何设置它,因为我希望该方法只是在基类中,适应正确的子类。

我也尝试在每个派生类中添加这样的东西,但我找不到在基类方法中使用它进行强制转换的方法:

private Type itemType = typeof(BaseReaction);

先感谢您!

c# interface casting dry derived-class
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.