繁体   English   中英

具有动态属性类型的DTO列表

[英]List of DTO with Dynamic type of propertie

我正在尝试创建一个这样的Dto:

public class GroupEventualityDto
{
    public int Id { get; set; }
    public int IdGroup { get; set; }
    public int IdEventuality { get; set; }
    public ???? Value { get; set; }
}

请注意,属性Value是一种动态类型(仅十进制,字符串或整数)。 我实现了添加List<GroupEventualityDto> ,其中GroupEventualityDto的数据类型为小数,整数或其他大小写类型。 如何实现呢?

进行所需操作的唯一方法是使用基类,然后继承该基类,并使此派生类具有通用性,如下所示:

public abstract class GroupEventualityDto
{
    public int Id { get; set; }
    public int IdGroup { get; set; }
    public int IdEventuality { get; set; }
}

public class GroupEventualityDto<T> : GroupEventualityDto
{

    public T Value { get; set; }
}

public static void Main(string[] args)
{
    var one = new GroupEventualityDto<int>() {Value = 123};
    var two = new GroupEventualityDto<string>() {Value = "string"};
    var three = new GroupEventualityDto<double>() {Value = 45.54};

    var list = new List<GroupEventualityDto>()
    {
        one,
        two,
        three
    };

    foreach (var val in list)
    {
        Console.WriteLine(val.GetType());
    }
}

但是,当您希望将其从列表中删除时,您将不得不将其撤回。

为什么不像这样的泛型呢?

public class GroupEventualityDto<T>
{
    public int Id { get; set; }
    public int IdGroup { get; set; }
    public int IdEventuality { get; set; }
    public T Value { get; set; }
}

如果我正确地理解了您的问题,那么您既想拥有一个通用类,又希望将Value的类型限制为特定的类型。

有效但相当丑陋的泛型类型限制

public class GroupEventualityDto<T>
{
    public int Id { get; set; }
    public int IdGroup { get; set; }
    public int IdEventuality { get; set; }
    public T Value { get; set; }

    public GroupEventualityDto(){
        if(!(Value is int || Value is decimal || Value is string)) throw new ArgumentException("The GroupEventualityDto generic type must be either an int, decimal or string");
    }
}

在第二次尝试中,我将检查Value的类型是否为预期的类型之一,如果不是这种情况,则抛出ArgumentException。

现在,当我使用

GroupEventualityDto<int> testTrue = new GroupEventualityDto<int>();

一切都会以我认为该问题旨在实现此类的方式进行。

如果我正在尝试使用一种不适用于该类的类型,如

GroupEventualityDto<float> testFalse = new GroupEventualityDto<float>();


// System.ArgumentException: The GroupEventualityDto generic type must be either an int, decimal or string

上面的异常将按预期抛出。

您可以在这里尝试工作代码 希望这种方法对您有所帮助!

话虽这么说,但如果将类型存储在有效类型的数组中,则可以使其更具可读性并增强可用性,但是不幸的是,我无法解决这个问题。


类型约束-在这里不起作用

乍一看,我会想到使用像

public class GroupEventualityDto<T> where T: int, decimal, string

会工作。 但是,事实证明这是行不通的。

“ int”不是有效的约束。 用作约束的类型必须是接口,非密封类或类型参数。

已经在这里提出一个密切相关的问题,事实证明,在这种情况下不能使用约束来约束类型约束。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM