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

时间:2019-04-23 19:56:35

标签: c# interface casting dry derived-class

我有一个基类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属性。

除了在AddItemassetType上进行强制转换外,它们都将使用完全相同的newItem方法。

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

我也尝试过在每个派生类中放入类似的内容,但是我找不到在基类方法中进行转换的方法:

private Type itemType = typeof(BaseReaction);

提前谢谢!

1 个答案:

答案 0 :(得分:0)

最适合我的解决方案是:

  • 创建一个CollectionItemBaseReaction派生的基类BaseCondition,它们具有相似的所有属性
  • 创建一个BaseCollectionReactionCollection派生的基类ConditionCollection,它们具有相似的所有属性

这样,我可以只引用CollectionItem中的基类BaseCollectionBaseCollectionInspector,并将我希望派生检查器唯一的所有方法设置为{{1} }

我确定这是我所使用的工具的特有功能,但是要点是有可能,您只需要查找相似类的公共部分,并为其创建父类即可。

不过感谢您的帮助:)

PS:我真的很喜欢C#,并且意识到即使没有使用任何类型的严格输入,PHP仍然令人困惑,即使我已经使用20多年了:)