【问题标题】:static typed object enumerable collection declaration [closed]静态类型对象可枚举集合声明
【发布时间】:2018-02-07 17:31:48
【问题描述】:

我有几个编辑器。每个编辑器都有特定性,例如数据库中的特定字段类型或可编辑或不可编辑。

所以我需要一组带有名称和属性的编辑器类型。我需要能够用集合填充组合框

如何声明每种类型并拥有类型列表?

我试试这个

public enum TemplateType
{TextBox,ColorPicker};

    public class TabloidBaseControl
{
    public static DbType DefaultFieldType { get { return DbType.String; } }
    public static int? DefaultFieldLength { get { return 20; } }
    public static int? DefaultFieldDecimal { get { return null; } }
}

public class TCColorPicker:TabloidBaseControl
{
    public new static int? DefaultFieldLength = 7;
}

public class TCTextBox: TabloidBaseControl
{
    public new static int? DefaultFieldLength = 20;
}

    public static Dictionary<TemplateType, TabloidBaseControl> TabloidControlList = new Dictionary<TemplateType, TabloidBaseControl> {
        {TemplateType.TextBox,new TCTextBox()},
        {TemplateType.ColorPicker,new TCColorPicker() }

    };

这是正确的方法吗?

【问题讨论】:

  • 您确定您发布的代码正确吗?
  • 是的,这是我的代码......但是车辆的例子不是一个好主意,我删除它
  • 好吧,你得到的代码有什么问题?你不想做什么?也就是说,这个问题还是很模糊的。你想完成什么?
  • 起初对不起我的英语。我有很多编辑器,每个编辑器都有相同的属性,例如数据库中需要的字段类型。我需要有一个此编辑器的列表以填充到组合框中,并从选定的值中找到数据库字段类型。
  • 我明白了那部分,但我不明白为什么这段代码不能做你想做的事。

标签: c# class static declaration


【解决方案1】:

您没有正确地进行类继承。在基类上使用虚拟属性,并在派生类中覆盖适当的属性,如下所示:

public enum TemplateType
{TextBox,ColorPicker};

public class TabloidBaseControl
{
  public virtual DbType DefaultFieldType
  {
    get { return DbType.String; }
  }

  public virtual int? DefaultFieldLength
  {
    get { return 20; }
  }

  public virtual int? DefaultFieldDecimal
  {
    get { return null; }
  }
}

public class TCColorPicker : TabloidBaseControl
{
  public override int? DefaultFieldLength
  {
    get { return 7; }
  }
}

public class TCTextBox : TabloidBaseControl
{
  public override int? DefaultFieldLength
  {
    get { return 20; }
  }
}

是的,您的字典将始终将对象作为基类的实例返回,因为它是这样定义的。但是,对象的运行时类型将是您添加的任何派生类,因此将从属性访问器返回正确的值。

【讨论】:

  • 感谢您的回复,我会尝试您的解决方案。有没有办法使用静态对象?
  • 不,为什么还要使用静态属性?
  • 我想使用对象作为类型,无需实例化
  • 没有实例化就没有继承。没有继承,就没有多态性。
  • 如果我不使用基类有没有办法建立一个集合
猜你喜欢
  • 2015-04-26
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 2011-06-01
  • 1970-01-01
  • 2011-06-17
  • 2022-01-23
  • 1970-01-01
相关资源
最近更新 更多