您可以使用继承。
这是最近工作的一个例子:
abstract public class AttributeVariant
{
string key;
string name;
public AttributeVariant(string key, string name)
{
this.key = key;
this.name = name;
}
public string GetKey()
{
return key;
}
public string GetName()
{
return name;
}
}
public class AttributeVariant<T> : AttributeVariant
{
T value;
public AttributeVariant(string key, string name, T value = default) : base(key, name)
{
this.value = value;
}
public object GetValue()
{
return value;
}
public void SetValue(T value)
{
this.value = value;
}
}
public class AttributeVariant<T, T2> : AttributeVariant<T>
{
T2 data;
public AttributeVariant(string key, string name, T value = default, T2 data = default) : base(key, name, value)
{
this.data = data;
}
public object GetData()
{
return data;
}
public void SetData(T2 data)
{
this.data = data;
}
}
这样我就可以将泛型类类型存储到一个简单的变量中,而不会出现任何问题。以下是我如何使用这些:
static Dictionary<string, AttributeVariant> AttributesList = new Dictionary<string, AttributeVariant>()
{
{ "age", new AttributeVariant<string>("age", "Age") },
{ "arms", new AttributeVariant<string>("arms", "Arms") },
{ "bridge", new AttributeVariant<string>("bridge", "Bridge") },
{ "color", new AttributeVariant<string>("color", "Model") },
{ "condition", new AttributeVariant<string, double>("condition", "Condition") },
{ "full_color", new AttributeVariant<string>("full_color", "Full Color") },
{ "gender", new AttributeVariant<string>("gender", "Gender") },
{ "height", new AttributeVariant<string>("height", "Height") },
{ "lenses", new AttributeVariant<string>("lenses", "Lenses") },
{ "material", new AttributeVariant<string>("material", "Material") },
{ "rim_type", new AttributeVariant<string>("rim_type", "Rim Type") },
{ "shape", new AttributeVariant<string>("shape", "Shape") },
};