c# - 通用类型的集合

标签 c# generics collections interface

<分区>

我有一个对象(表单),其中包含一个集合(.Fields),我想在其中包含通用类(FormField)的实例。

简单来说,FormField 是这样定义的:

public class FormField<T>
{
    private Form Form;
    public T Value { get; set; }
    public string Name { get; set; }

    public void Process()
    {
        // do something
    }

    public FormField(Form form, string name, T value)
    {
        this.Name = name;
        this.Value = value;
        this.Form = form;
    }
}

这让我可以拥有 FormField、FormField 等,这部分工作得很好。 我想要的是一个“Formfields”的集合,无论类型如何,但我被迫定义一个类型(看起来),例如:

public class Form
{

    string Code { get; set; }
    string Title { get; set; }
    int Year { get; set; }
    Guid ClientID { get; set; }

    ICollection<FormField<int>> Fields { get; set; }
}

我想,我想要的是一个接口(interface),它允许我抽象类型信息,从而将集合类型化为(例如)IFormField 而不是 FormField<>

但如果不在界面中强键入集合,我看不出如何定义它...

任何帮助(包括任何替代解决方案!)将不胜感激!

谢谢,本

最佳答案

这里有一些代码来完成 Jon 的回答:

public interface IFormField
{
    string Name { get; set; }
    object Value { get; set; }
}

public class FormField<T> : IFormField
{
    private Form Form;
    public T Value { get; set; }
    public string Name { get; set; }

    public void Process()
    {
        // do something
    }

    public FormField(Form form, string name, T value)
    {
        this.Name = name;
        this.Value = value;
        this.Form = form;
    }

    // Explicit implementation of IFormField.Value
    object IFormField.Value
    {
        get { return this.Value; }
        set { this.Value = (T)value; }
    }
}

在你的表单中:

ICollection<IFormField> Fields { get; set; }

关于c# - 通用类型的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3777057/

相关文章:

java - 了解 Fastutil 内部的资源

c# - 使用构建后事件在 Visual Studio 中重命名项目输出会产生错误

c# - 使用特定值解决 MemberChangeConflict

c# - 如何在 C# 中填写 RSAParameters 值

c# - 在 Dictionary C# 中使用泛型类

java - JMenuBar抽象按钮工厂不添加按钮

java - 从 ArrayList 获取特定类型的第一个元素

c# - 进行切换以针对数组中的项目进行操作

java - 将父类(super class)对象放入下限通配符列表时出错

scala - 为什么 scala 的集合默认不是 'views'?