同一个集合不同泛型Ť [英] Different Generics T in the same collection

查看:116
本文介绍了同一个集合不同泛型Ť的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public abstract Column<T>
{
   private T Value {get;set;}    

   public abstract string Format();

}

public class DateColumn : Column<DateTime>
{
   public override string Format()
   {
      return Value.ToString("dd-MMM-yyyy");
   }
}

public class NumberColumn : Column<decimal>
{
   public override string Format()
   {
      return Value.ToString();
   }
}



我是加入到这些泛型集合问题。我知道它可能的,但我怎么能存储在一个集合多种类型等。

The problem I have is adding these into a generic collection. I know its possible but how can I store multiple types in a collection etc

IList<Column<?>> columns = new List<Column<?>()



我真的对实现这一感激任何建议目标。目标是具有存储在相同的列表不同的列类型。它值得一提的我使用NHibernate和鉴别加载适当object.Ultimately价值需要有类的类型。

I would really appreciate any advice on achieving this goal. The goal being having different column types stored in the same List. Its worth mentioning I am using NHibernate and the discriminator to load the appropriate object.Ultimately the Value needs to have the type of the class.

非常感谢您的帮助提前。

Many thanks for your help in advance.

推荐答案

在为存储在列表< T> 在一起列必须有一个共同的基本类型。最近的公共基类的 DateColumn NumberColumn 对象 。从专栏<无论派生; T> 而是列℃的特殊和不同的实例; T>

In order to be stored in a List<T> together the columns must have a common base type. The closest common base class of DateColumn and NumberColumn is object. Neither derives from Column<T> but instead a specific and different instantiation of Column<T>.

这里的一个解决方案是引入一个非通用键入这专栏< T> ; 从派生并存储在列表

One solution here is to introduce a non-generic Column type which Column<T> derives from and store that in the List

public abstract class Column { 
  public abstract object ValueUntyped { get; }
}

public abstract class Column<T> : Column {
  public T Value { get; set; }
  public override object ValueUntyped { get { return Value; } }
}

...

IList<Column> list = new List<Column>();
list.Add(new DateColumn());
list.Add(new NumberColumn());

这篇关于同一个集合不同泛型Ť的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆