我有一个基类BaseCollectionInspector
,它有两个派生类:ReactionCollectionInspector
和ConditionCollectionInspector
.
基类有这个方法:
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
方法,除了在assetType
and上进行强制转换newItem
。
我正在尝试正确学习 C#,并希望使用 DRY 原则,即使复制代码很容易。我想我可能可以使用接口,但我不确定如何设置它,因为我希望该方法仅在基类中,以适应正确的子类。
我也尝试在每个派生类中放置类似的东西,但我找不到一种方法来使用它在基类方法中进行强制转换:
private Type itemType = typeof(BaseReaction);
先感谢您!