C
C#9mo ago
항암제

Derived class , BaseClass, Dictionary

Hello! I have a question. I declared Dictionary<int, BaseClass>, initialized the variables and functions of the BaseClass in a class that inherits from it. When I called a method from the dictionary, I confirmed that the overridden method was invoked. Can you explain how this works and why it's possible? I tried searching but couldn't find much. I'll attach a picture.
No description
No description
No description
No description
6 Replies
Pobiega
Pobiega9mo ago
No idea why you made this so incredibly convoluted with unity, weird class and method names and using an enum in one place and an int in another.. but what I think your question is about is how Test002 can be considered an object of type Test001? is that correct?
항암제
항암제OP9mo ago
Thank you for your response. I'm currently working on creating a card game as a learning project. As I contemplate how to manage the cards, I wanted to organize them within a data structure. To differentiate between the cards, I intended to assign unique ID values to each card. When I input a card's ID, I aim to retrieve its Name, Cost, and Effect from the data structure for use. I tested this, and the attached picture shows the result. My question is, within the data structure, there is a BaseClass, and when I make a call, it seems to output the method of the child class that overrides the base class method. I'm curious if this behavior is expected, and I'd like to understand how it works internally.
Pobiega
Pobiega9mo ago
This is polymorphism at its most basic form in C# Your base class declares a virtual method your child classes override that method, providing their own code
MODiX
MODiX9mo ago
Pobiega
REPL Result: Success
class BaseClass
{
public virtual void Act()
{
Console.WriteLine("Baseclass");
}
}
class ChildClass : BaseClass
{
public override void Act()
{
Console.WriteLine("Childclass");
}
}

BaseClass x = new ChildClass();
x.Act();
class BaseClass
{
public virtual void Act()
{
Console.WriteLine("Baseclass");
}
}
class ChildClass : BaseClass
{
public override void Act()
{
Console.WriteLine("Childclass");
}
}

BaseClass x = new ChildClass();
x.Act();
Console Output
Childclass
Childclass
Compile: 446.227ms | Execution: 27.035ms | React with ❌ to remove this embed.
Pobiega
Pobiega9mo ago
this is a more simple example that does the exact same thing as your code does
항암제
항암제OP9mo ago
Thank you. Let me check the official letter about polymorphism
Want results from more Discord servers?
Add your server