我有一种情况,我需要一个类,它需要包含有关运行时变化的信息,例如:
class Info<T>
{
public T Max { get; set; }
public T Min { get; set; }
public T DefaultValue { get; set; }
public T Step { get; set; }
// Some other stuff
}
我必须在字典中存储此类的许多实例,但问题是要使用字典我必须声明一种类型,例如
Dictionary<string, Info<int>> dict = new Dictionary<string, Info<int>>();
在这种情况下,我无法添加其他类型的信息,例如Info<double>
.
我想要类似的东西,我在下面的案例中删除了通用版本。
{"Price", new Info{Min=100,Max=1000,DefaultValue=200,Step=50}}
{"Adv", new Info{Min=10.50,Max=500.50,DefaultValue=20.50,Step=1.5}}
{"Answer", new Info{Min=false,Max=false,DefaultValue=false,Step=false}}
我可以使用 Dictionary<string, Object> dict = new Dictionary<string, Object>();
但是当我取回字典项时,我不知道那是什么类型,我也需要知道类型,例如对于 Price
它是 int 而 Adv 是 double ,我如何在运行时知道它?
实际上我想创建一个验证器(我正在使用 .Net Compact Framework 3.5/不能使用任何内置系统,如果它存在)例如如果我有一个如下所示的类..
class Demo
{
public int Price { get; set; }
public float Adv { get; set; }
public static bool Validate(Demo d)
{
List<string> err = new List<string>();
// here I have to get Info about the Price
// from dictionary, it can be any storage
Info priceInfo = GetPriceInfo("Price");
if (d.Price < priceInfo.Min)
{
d.Price = priceInfo.Min;
err.Add("price is lower than Min Price");
}
if (d.Price > priceInfo.Max)
{
d.Price = priceInfo.Max;
err.Add("price is above than Max Price");
}
// need to do similar for all kinds of properties in the class
}
}
所以想法是将验证信息存储在一个地方(在字典或其他地方),然后在验证时使用该信息,我也想知道我是否可以以更好的方式设计上述场景?
也许有更好的方法,请问有什么指导方针吗?
最佳答案
您可以使用非泛型基类:
public abstract class Info {
}
public class Info<T> : Info {
}
现在所有不同的泛型类型都继承自相同的基类型,因此您可以在字典中使用它:
Dictionary<string, Info> dict = new Dictionary<string, Info>();
可以在基类中定义接口(interface)不依赖泛型的属性和方法,并在泛型类中实现。这样您就可以在不指定通用类型的情况下使用它们。
对于需要类型的方法,您需要针对每种类型的特定代码。您可以使用 is
和 as
运算符来检查类型:
Info<int> info = dict[name] as Info<int>;
if (info != null) {
int max = info.Max;
}
关于c# - 如何在 C# 中制作/设计一个在运行时可以具有不同类型成员的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14738837/