c# - 用类型安全泛型方法替换非类型安全

标签 c# generics type-safety

我正在寻找一种方法来替换以下内容:

public class NonTypeSafe
{
    private List<object> contents = new List<object>();
    public List<object> Contents {get { return contents; }};

    public NonTypeSafe(params object[] arguments)
    {
        foreach(object arg in arguments)
        {
            contents.Add(arg);
        }
    }
}

使用类型安全的东西。目的是拥有一个对象,我可以在其中添加许多不同类型的对象。目前,检索对象时必须进行检查,以确定它们是否属于正确的类型/顺序是否正确。

目前我有以下内容:

public class TypeSafe<T1>
  {
    protected List<object> ArgList = new List<object>();

    private readonly T1 arg1;

    public TypeSafe(T1 arg1)
    {
      ArgList.Add(arg1);
      this.arg1 = arg1;
    }

    public T1 Arg1
    {
      get { return (T1) ArgList[ArgList.IndexOf(arg1)]; }
    }
  }



  public class TypeSafe<T1, T2> : TypeSafe<T1>
  {

    private readonly T2 arg2;

    public TypeSafe(T1 arg1, T2 arg2) : base(arg1)
    {
      ArgList.Add(arg2);
      this.arg2 = arg2;
    }

    public T2 Arg2
    {
      get { return (T2) ArgList[ArgList.IndexOf(arg2)]; }
    }
  }

依此类推,将新类添加到我合理预期的最大数量参数。有没有更好的方法来实现这一点?

最佳答案

你是在重新发明 System.Tuple

A tuple is a data structure that has a specific number and sequence of elements. An example of a tuple is a data structure with three elements (known as a 3-tuple or triple) that is used to store an identifier such as a person's name in the first element, a year in the second element, and the person's income for that year in the third element.

关于c# - 用类型安全泛型方法替换非类型安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7283802/

相关文章:

c# - 如何使用自定义 C# 函数替换多次出现的子字符串?

c# - 将参数作为路径段发送在 ServiceStack 中不起作用

java - 作为变量的通用参数 - Java

c# - 将 SOAP header 添加到 ASMX 服务请求

java - Java 中的嵌套类型参数

Java 泛型与类和接口(interface) - 一起

generics - Kotlin:类的通用参数及其解析方式

Scala 类型安全与开销(类型与类)

c++ - `int*[1]` 和 `int(*)[1]` 有什么区别?

c# - 正则表达式匹配 C# 代码中的 SQL 关键字