如何在 C# 中返回命名元组?

我有一个属性返回两个类型的项目DateTime。返回这些值时,我必须将它们引用为Item1and Item2。我如何返回自定义名称,例如


filter?.DateRanges.From

filter?.DateRanges.To

 


public Tuple<DateTime, DateTime> DateRanges

{

    get

    {

        From = DateTime.Now.AddDays(-1).Date.AddMonths(-1);

        To = DateTime.Now.AddDays(-1).Date;


        if (Preset != 0)

        {

            if (Preset == DatePreset.SpecificRange)

            {

                From = From.Date;

                To = To.Date;

            }

            else

            {

                var dateRange = DateTime.Today.AddDays(-1).GetDateRangeByPreset(Preset);

                From = dateRange.From;

                To = dateRange.To;

            }

        }


        return new Tuple<DateTime, DateTime>(From, To);

    }

用法:


var from = filter?.DateRanges.Item1;

var to = filter?.DateRanges.Item2;


繁花如伊
浏览 151回答 2
2回答

皈依舞

像这样:public (DateTime Start, DateTime End) DateRanges{&nbsp; &nbsp; get&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return (DateTime.MinValue, DateTime.MaxValue);&nbsp; &nbsp; }}注意:这需要最新版本的 C# 和 .Net。顺便提一下,注意这种使用模式:var from = filter?.DateRanges.Start;var to = filter?.DateRanges.End;这是低效的,因为它会导致创建两个相同的元组。这个更好:var range = filter?.DateRanges;if (range.HasValue){&nbsp; &nbsp; var from&nbsp; = range.Value.Start;&nbsp; &nbsp; var to&nbsp; &nbsp; = range.Value.End;}但是请注意,元组不能为空(它们是值类型),因此您可以这样编写:if (filter != null){&nbsp; &nbsp; var range = filter.DateRanges;&nbsp; &nbsp; var from&nbsp; = range.Start;&nbsp; &nbsp; var to&nbsp; &nbsp; = range.End;&nbsp; &nbsp; ...}

月关宝盒

class Program{&nbsp; &nbsp; static void Main(string[] args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; test t = new test();&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(t.NamedTuple.start);&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(t.NamedTuple.stop);&nbsp; &nbsp; &nbsp; &nbsp; Console.Read();&nbsp; &nbsp; }}class test{&nbsp; &nbsp; DateTime From;&nbsp; &nbsp; DateTime To;&nbsp; &nbsp; public (DateTime start, DateTime stop) NamedTuple&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; From = DateTime.Now.AddDays(-1).Date.AddMonths(-1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; To = DateTime.Now.AddDays(-1).Date;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return (From, To);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP