C# 如何在一个Dictionary的Value中放入不同的派生类
时间: 2024-02-23 22:58:39 浏览: 22
在C#中,可以在Dictionary的Value中放入不同的派生类,可以通过使用抽象类或接口作为Value类型来实现。具体步骤如下:
1. 定义一个抽象类或接口,作为Dictionary的Value类型。
```csharp
public abstract class MyBaseClass
{
public abstract void MyMethod();
}
public class MyDerivedClass1 : MyBaseClass
{
public override void MyMethod()
{
// 实现自定义方法
}
}
public class MyDerivedClass2 : MyBaseClass
{
public override void MyMethod()
{
// 实现自定义方法
}
}
// 或者使用接口
public interface IMyInterface
{
void MyMethod();
}
public class MyDerivedClass1 : IMyInterface
{
public void MyMethod()
{
// 实现自定义方法
}
}
public class MyDerivedClass2 : IMyInterface
{
public void MyMethod()
{
// 实现自定义方法
}
}
```
2. 创建一个Dictionary,将抽象类或接口作为Value类型。
```csharp
Dictionary<int, MyBaseClass> myDictionary = new Dictionary<int, MyBaseClass>();
// 或者使用接口
Dictionary<int, IMyInterface> myDictionary = new Dictionary<int, IMyInterface>();
```
3. 向Dictionary中添加不同的派生类对象。
```csharp
myDictionary.Add(1, new MyDerivedClass1());
myDictionary.Add(2, new MyDerivedClass2());
```
4. 调用对应的派生类方法。
```csharp
myDictionary[1].MyMethod(); // 调用MyDerivedClass1的MyMethod方法
myDictionary[2].MyMethod(); // 调用MyDerivedClass2的MyMethod方法
```