Mixed type Dictionary

  • Thread starter Thread starter DonJefe
  • Start date Start date
D

DonJefe

Is there any way to have a mixed type Dictionary object? For example
something like:


dictionary.Add(3, "foobar");
dictionary.Add("foo", 33444);

I am trying to make a generic parameter list without reverting to
Dictionary<object, object>. Any ideas on where to look for this sort of
thing? I have been doing a lot of work with generics lately, but have
not found anything to fit the bill.

Thanks.
 
Well, it is hard to do without boxing... but can be done...

Look at the following; you can (as examples);

ParameterSet ps = new ParameterSet();
ps.Add("Test", 5);
ps.Add<int>("SomeParam");
int val = ps.GetValue<int>("Test");
ps.SetValue("SomeParam", 17);
IParameter param = ps["Test"];
param.Type...
param.Value...
param.Name...

etc

Marc

===

public interface IParameter
{
string Name { get;}
object Value { get; set;}
Type Type { get; }
}
public interface IParameter<T> : IParameter
{
new T Value { get; set;}
}
public class Parameter<T> : IParameter, IParameter<T>
{
public Type Type { get { return typeof(T); } }
readonly string name;
public string Name { get { return name; } }
T value;
public T Value {
get { return this.value; }
set { this.value = value; }
}
object IParameter.Value
{
get { return Value; }
set { Value = (T) value; }
}
public Parameter(string name) : this(name, default(T)) {}
public Parameter(string name, T value) {
this.name = name;
this.value = value;
}
}
public class ParameterSet
{
readonly Dictionary<string, IParameter> parameters = new
Dictionary<string, IParameter>();
IParameter this[string name]
{
get { return parameters[name]; }
}
void Add(IParameter parameter)
{
parameters.Add(parameter.Name, parameter);
}
void Add<T>(string name) {
Add(name, default(T));
}
void Add<T>(string name, T value)
{
Add(new Parameter<T>(name, value));
}
T GetValue<T>(string name)
{
return ((IParameter<T>)parameters[name]).Value;
}
void SetValue<T>(string name, T value)
{
((IParameter<T>)parameters[name]).Value = value;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top