如何在类中使用任意类型类并调用其指定方法?
Hey there! Let's work through your problem—what you're looking for is exactly the kind of scenario that interfaces were made for in C# (especially in Unity, since you're using MonoBehaviour). Here's how to fix this step by step:
Step 1: Define an Interface to Set the "Contract"
First, create an interface that declares the method you want to call (next() in this case). This interface acts as a common "contract"—any class that implements this interface promises to have the next() method.
public interface IChoiceHandler { // Declare the method all compatible classes must implement void next(); }
Step 2: Update Your Existing Class to Implement the Interface
Modify your original choiceHandler class to implement this interface. It already has the next() method, so you just need to add the interface to its definition:
public class choiceHandler : MonoBehaviour, IChoiceHandler { // Your existing next() method stays exactly the same public void next() { // Put your original logic here (like advancing dialogue, etc.) } }
Step 3: Refactor DialogueSuper to Use the Interface
Instead of declaring ch as a specific choiceHandler type, use the interface type. This lets you assign any class that implements IChoiceHandler to ch, not just your original one.
public class DialogueSuper : MonoBehaviour { // Now this can hold ANY class that implements IChoiceHandler public IChoiceHandler ch = null; void Start () { } void Update () { } public void end() { // Always add a null check to avoid runtime crashes! if (ch != null) { ch.next(); } } }
How This Solves Both Your Requirements
- Using any type of class: By using the
IChoiceHandlerinterface type, you can assign any class that implements this interface toch—whether it's your originalchoiceHandler, a newAdvancedChoiceHandler, or even a mock class for testing. - Calling the specified method across any class: Since the interface guarantees the
next()method exists, you can safely callch.next()no matter what concrete class is assigned. Unity will handle the rest at runtime.
Bonus Tip for Unity
In the Unity Inspector, you can still drag and drop any component that implements IChoiceHandler onto the ch field—just like you did with the original choiceHandler class. No extra setup needed!
内容的提问来源于stack exchange,提问作者user6369603

