c# - 如何在 C# 中制作/设计一个在运行时可以具有不同类型成员的类

标签 c#

我有一种情况,我需要一个类,它需要包含有关运行时变化的信息,例如:

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)不依赖泛型的属性和方法,并在泛型类中实现。这样您就可以在不指定通用类型的情况下使用它们。

对于需要类型的方法,您需要针对每种类型的特定代码。您可以使用 isas 运算符来检查类型:

Info<int> info = dict[name] as Info<int>;
if (info != null) {
  int max = info.Max;
}

关于c# - 如何在 C# 中制作/设计一个在运行时可以具有不同类型成员的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14738837/

相关文章:

c# - 用户事件概况和统计数据

c# - C# 替换字符串的部分内容

c# - 从 html 中删除除文本以外的所有内容

c# - 引发 "potentially dangerous Request.Form value"错误的条件是否取决于 .NET 配置和版本?

c# - MEF,为什么创建了一个相同的导出插件的相同副本?

c# - 处理一个不会在C#中引发异常的类

c# - MEF 通用进口

c# - 从引发事件的外部线程更新控件

c# - 在带有 Entity Framework 的 ASP.NET MVC 中,此上下文仅支持原始类型或枚举类型

c# - 使用 Rotativa 从多个 View 生成 pdf?