简体   繁体   中英

How can you properly instantiate a Tuple type?

Having these enums ReportType, ReportField and ReportDimension with the following specification:

Basically I have three report types and each one is kind of unique, one supports some of the ReportFields and some of the ReportDimensions (doesn't matter which), I would like to create a dictionary that has 3 KeyValuePair items (for every report type) and has tuple as value that looks like this:

private readonly Dictionary<ReportType, (List<ReportField>, List<ReportDimension>)> _reportTypeDimensionMappings;

I wanted to directly instantiate this structure but the way I intend to, gives me build errors:

private readonly Dictionary<ReportType, (List<ReportField>, List<ReportDimension>)> _reportTypeDimensionMappings = new Dictionary<ReportType,
        (List<ReportField>, List<ReportDimension>)>
    {
        {ReportType.Session, new (List<ReportField>, List<ReportDimension>)
            {
                new List<ReportField>
                {

                },
                new List<ReportDimension>
                {

                }
            }
        },

    };

Is there an explicit good practice way to instantiate the value of a dictionary that's a Tuple ?

It's already been suggested that you shouldn't be using a Tuple here, and I agree, but to answer your question, the syntax is quite simple:

private readonly Dictionary<ReportType, (List<ReportField>, List<ReportDimension>)> _reportTypeDimensionMappings = 
    new Dictionary<ReportType, (List<ReportField>, List<ReportDimension>)>
    {
        {ReportType.Session, (new List<ReportField>(), new List<ReportDimension>()) }
    };

It seems like a class would be better suited for what you need. You could create a class called Report that contains your List<ReportField> and List<ReportDimension> properties.

Tuples are useful for when you need a short-lived, relatively-small collection of values or objects to be treated as one thing (ie a return from a method), but there's really not much cost to creating a dedicated class for these types of things either. As Daniel A. White pointed out in your comments section, it makes your code harder to read, and given you don't need much of a reason to create a class for any purpose, I'd say any reason is good enough.

You can create a Tuple object by calling Tuple t = Tuple.Create(object1, object2); then you can get the values by t.Item1 for object1 and t.Item2 for object2

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