【发布时间】:2015-05-17 05:15:06
【问题描述】:
有没有办法使用类here 描述的方法在一个列表中拥有多个结构类型?
参考一个告诉我从抽象类(结构不可能)或接口继承的答案,我想出了这个:
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")));
哪个应该起作用,因为它与类一起使用,并且我认为结构确实支持接口的继承?
我得到了这个错误:
Assets/Test.cs(51,22): error CS0305: Using the generic type `Memorable<T>' requires `1' type argument(s)
在列表声明行中
或者你能引导我找到更好的解决方案吗?关于性能,我可能需要存储数千个这样的结构。我不确定在这种方法是否可行的情况下,从抽象类继承的类是否更合适......
你能给我建议吗?
【问题讨论】:
-
为什么你想这样做?我相信还有其他方法可以解决您的性能问题
-
请注意,将结构存储为接口会完全破坏您可能追求的任何性能优势,因为只会存储对装箱实例的引用
-
那么您认为使用具有抽象类作为基础的类会更好吗? :|我现在正在进行运行时测试:)
标签: c# list inheritance struct types