简体   繁体   中英

c# - Cannot convert from List<DateTime?> to List<dynamic>

I am trying to create an attribute in a list that takes different types. This is my class:

public class ChartData
{
    public string id { get; set; }
    public List<dynamic> data { get; set; }

    public ChartData()
    {
    }

    public ChartData(string id, List<DateTime?> data)
    {
        this.id = id;
        this.data = data;
    }
}

    public ChartData(string id, List<float?> data)
    {
        this.id = id;
        this.data = data;
    }

    public ChartData(string id, List<int?> data)
    {
        this.id = id;
        this.data = data;
    }

In the code I use the data list to store DateTime? , float? or int? data. What do I do to be able to store these different types in one class attribute?

I am getting the error:

Argument 2: cannot convert from 'System.Collections.Generic.List<System.DateTime?>' to 'System.Collections.Generic.List<dynamic>'

I would recommend using Generics if you know the type prior to instantiation

public class ChartData
{
   public string id { get; set; }
}

public class ChartData<T> : ChartData
{
    public List<T> data { get; set; }

    public ChartData()
    {
    }

    public ChartData(string id, List<T> data)
    {
        this.id = id;
        this.data = data;
    }
}

Usage:

ChartData<int> intData = new ChartData<int>("ID1", new List<int>());
ChartData<DateTime> dateData = new ChartData<DateTime>("ID1", new List<DateTime>());
ChartData<float> floatData = new ChartData<float>("ID1", new List<float>());



List<ChartData> list = new List<ChartData>() {
    intData,
    dateData,
    floatData
};

I think change below should work: FROM

 public List<dynamic> data { get; set; }

TO

 public dynamic data { get; set; }

If it suits your case you can use covariant collection like this:

IReadOnlyList<dynamic> data;
data = new List<string>();

But it works with reference types only.

If you don't care what type is it you can use List for your data.

For more convenient access you can use something like this:

private IList data;
public IEnumerable<dynamic> Data { get { return data.OfType<dynamic>(); } }

Hope it helps.

You may use LINQ to convert list items' type:

public ChartData(string id, List<DateTime?> data)
{
    this.id = id;
    this.data = data.Cast<dynamic>().ToList();
}

Important note: in this case you're creating a duplicate of the list and changes in the caller's instance of the list won't be reflected in the ChartData 's instance (which is probably even better, though.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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