c# - 一个列表中的多个结构类型

标签 c# list inheritance struct types

有没有办法使用为类描述的方法在列表中拥有多个结构类型 here

引用一个告诉我从抽象类(对于结构来说不可能)或接口(interface)继承的答案,我想到了这个:

public interface IMemorable {}

public struct Memorable<type> : IMemorable where type : struct 
{
    private type Data;

    public Memorable<type> (type data) 
    {
        Data = data;
    }
}

并以这种方式实现列表:

List<Memorable> memorables;
memorables.Add (new Memorable<someStruct> ());
memorables.Add (new Memorable<otherStruct> (new otherStruct (6, "Six")));

哪个应该工作,因为它与类一起工作,我认为结构确实支持接口(interface)的继承?

虽然我得到了这个错误:

Assets/Test.cs(51,22): error CS0305: Using the generic type `Memorable<T>' requires `1' type argument(s)

在列表声明行

或者你能给我一些更好的解决方案吗...关于性能,我可能需要存储数千个这样的结构。我不确定如果这种方法能以某种方式起作用,那么从抽象类继承的类是否更适合...

你能给我建议吗?

最佳答案

是的(有一些小的更正),但它没有用:

public interface IMemorable {}

public struct Memorable<T> : IMemorable where T : struct 
{
    private T Data;

    public Memorable(T data) 
    {
        Data = data;
    }
}

List<IMemorable> memorables = new List<IMemorable>();
memorables.Add(new Memorable<someStruct>(new someStruct()));
memorables.Add(new Memorable<otherStruct>(new otherStruct(6, "Six")));

(请注意,通常泛型类型称为 TSomething(TS 大写))/p>

因为那时您所拥有的只是一个IMemorable,您不能使用它来访问T 数据

我要补充一点,一般来说,struct(以及所有值类型)和接口(interface)不能很好地混合,因为将 struct 强制转换为接口(interface)会导致其装箱(以及结构副本的创建),只有一个异常(exception)(此处不相关)

关于c# - 一个列表中的多个结构类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29053980/

相关文章:

javascript - 如何在 JavaScript 中获取所有类子级的列表?

inheritance - 如何在 Neo4j 中使用类型层次结构?

c# - 如何解析不同格式的地理坐标

c# - 如何在 Windows 窗体中创建垂直导航栏?

.net - 检查字符串列表是否包含值

转换 double < -> char

c# - 强制 .NET 类型实例化为 COM

c# - 将 xml 反序列化为从基类继承的类

python - 将双端队列对象转换为列表

java - 如何使用泛型在 Java 中创建通用方法?