这个问题在这里已经有了答案:
How do I create a heterogeneous collection of objects?
(1 个回答)
1年前关闭。
在 C# 中,我可以创建一个列表并向其中添加不同类型的项目。只要他们继承基类。例如:
using System;
using System.Collections.Generic;
class Parent
{
public int p;
public Parent(int p)
{
this.p = p;
}
}
class A : Parent
{
public int a;
public A(int p, int a) : base(p)
{
this.a = a;
}
}
class B : Parent
{
public int b;
public B(int p, int b) : base(p)
{
this.b = b;
}
}
class Program
{
static void Main(string[] args)
{
List<Parent> list = new List<Parent>();
A a = new A(10, 20);
B b = new B(30, 40);
list.Add(a);
list.Add(b);
A l_a = list[0] as A;
B l_b = list[1] as B;
Console.WriteLine(String.Format("{0}, {1}", l_a.p, l_a.a)); // 10, 20
Console.WriteLine(String.Format("{0}, {1}", l_b.p, l_b.b)); // 30, 40
}
}
Rust 不是一种面向对象的编程语言,但我想知道是否可以实现类似的东西。有方法吗?
最佳答案
您可以创建 Enum
并将其不同的变体存储在向量中。
示例:
use std::fmt::{Display, Formatter};
struct A {
a: i32,
}
impl A {
fn new(a: i32) -> Self {
A { a }
}
}
struct B {
b: i32,
}
impl B {
fn new(b: i32) -> Self {
B { b }
}
}
enum Parent {
ChildA(i32, A),
ChildB(i32, B),
}
impl Display for Parent {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Parent::ChildA(p, a) => write!(f, "{}, {}", p, a.a),
Parent::ChildB(p, b) => write!(f, "{}, {}", p, b.b),
}
}
}
fn main() {
let mut vec = Vec::new();
let a = Parent::ChildA(10, A::new(20));
let b = Parent::ChildB(30, B::new(40));
vec.push(a);
vec.push(b);
let l_a = vec.get(0).unwrap();
let l_b = vec.get(1).unwrap();
println!("{}", l_a);
println!("{}", l_b);
}
关于list - 列出 Rust 中的不同类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62299911/