我正在寻找一种方法来替换以下内容:
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/