如何创建未知值类型的字典对象列表?
问题描述:
我正在创建一个CInformation
类,其中将包含各种类型的信息。它将公开的一种信息是Parameters
。每个参数可以键入以下任何类型:int
,short
,string
。此外,根据string
键,任何parameter
可能有多个可能的值。所以我想创建一个Dictionary<string, T>
来保存一个参数的所有可能的值,但是当我尝试声明我的Parameters
列表时出现问题。我创建了以下类:如何创建未知值类型的字典对象列表?
public class CParameter<T>
{
public object ParameterType { get; set; }
public Dictionary<string,T> ValueByString;
}
public class CInformation
{
public string Version { get; set; }
public string Name{ get; set; }
public List<CParameter<object>> Parameters; // cannot cast any of my types to object, obviously!
}
任何建议,我怎么能拿我的身边问题?我打开不同的解决方案来解决我的问题,不一定是我上面的设计。谢谢。
编辑:我想要实现的主要特点是能够有一个不同值类型的字典列表。
答
使用object
专门化一个泛型类型是相当可疑的。如果你这样做,你甚至可以根本不使用泛型类型。 :-)
我觉得这里的问题是,你希望你的CParameter<T>
实例被专门用于不同的参数类型,并且希望在CInformation
类的参数列表包含不同类型的CParameter<T>
。
换句话说:
namespace Scratch
{
class Program
{
static void Main(string[] args)
{
CParameter<int> ints = new CParameter<int>();
CParameter<long> longs = new CParameter<long>();
CInformation info = new CInformation();
info.AddParameter(ints);
info.AddParameter(longs);
CParameter<int> ints2 = info.GetParameter<int>();
// ints2 and ints will both refer to the same CParameter instance.
}
}
public class CParameter<T>
{
public Type ParameterType { get { return typeof(T); } }
public Dictionary<string, T> ValueByString;
}
public class CInformation
{
public string Version { get; set; }
public string Name { get; set; }
private List<object> parameters;
public CInformation()
{
this.parameters = new List<object>();
}
public void AddParameter<T>(CParameter<T> parameter)
{
this.parameters.Add(parameter);
}
public CParameter<T> GetParameter<T>()
{
foreach (object parameter in this.parameters)
{
if (parameter is CParameter<T>)
return (CParameter<T>)parameter;
}
throw new Exception("Parameter type " + typeof(T).FullName + " not found.");
}
}
}
注意,在例子中,List<object>
也可以同样是ArrayList
。
此外,我有一个预感,你要检索这些CParameter
对象的名称,而不是仅仅通过类型。因此,请考虑将名称属性添加到CParameter
,并为GetParameter
方法添加一个名称参数。然后遍历列表以找到名称正确的属性。在返回之前投射结果将验证该类型是否是您所期望的类型。
或者更好的是,将参数存储在Dictionary<string,object>
而不仅仅是一个列表中,并使用参数名称作为关键字。
您能否使'C信息'也通用,并使'公开列表>参数;'。我不确定我是否理解了您的问题 –
2014-11-03 18:56:17
您可能还想从'object'将'CParameter.ParameterType'更改为'T'。 – Michael 2014-11-03 18:58:55
不是真的,因为'Parameters'列表应该有多个CParameter对象,每个对象都是不同的类型。编辑:是的,你对'ParameterType'是正确的。 – mbadawi23 2014-11-03 19:01:00