将System.DayOfWeek转换为Microsoft.Office.Interop.Outlook.OlDaysOfWeek

时间:2019-04-16 10:53:12

标签: c# outlook-api

是否可以将System.DayOfWeek的值直接转换为Microsoft.Office.Interop.Outlook.OlDaysOfWeek的值。像这样:

var day = DayOfWeek.Friday;
OlDaysOfWeek days = ConvertToDaysOfWeek(day);

4 个答案:

答案 0 :(得分:2)

您可以尝试以下方法:

var olDay = (OlDaysOfWeek) Enum.Parse(typeof(OlDaysOfWeek), $"ol{systemDay}");

答案 1 :(得分:2)

要在不使用字符串操作的情况下执行此操作,请使用以下选项:

public OlDaysOfWeek ConvertToDaysOfWeek(DayOfWeek day)
{
    return (OlDaysOfWeek)Math.Pow(2, (int)day); 
}

答案 2 :(得分:1)

最简单的switch语句可能是最有效的:

public OlDaysOfWeek ConvertToDaysOfWeek(DayOfWeek day)
{
  switch (day)
  {
    case DayOfWeek.Monday: return OlDaysOfWeek.olMonday;
    case DayOfWeek.Tuesday: return OlDaysOfWeek.olTuesday;
    case DayOfWeek.Wednesday: return OlDaysOfWeek.olWednesday;
    case DayOfWeek.Thursday: return OlDaysOfWeek.olThursday;
    case DayOfWeek.Friday: return OlDaysOfWeek.olFriday;
    case DayOfWeek.Saturday: return OlDaysOfWeek.olSaturday;
    case DayOfWeek.Sunday: return OlDaysOfWeek.olSunday;
    default: throw new ArgumentOutOfRangeException("What day is this?", "day");
  }
}

或者,您可以解析该值并根据枚举值名称返回映射的值。

public OlDaysOfWeek ConvertToDaysOfWeek(DayOfWeek day)
{
  return (OlDaysOfWeek) Enum.Parse(typeof(OlDaysOfWeek), "ol" + day.ToString());
}

OlDaysOfWeek枚举使用2的幂序列,通常在将值组合为按位标志时使用。 DaysOfWeek有一个简单的线性序列,反映为0-6-这就是为什么您无法使用后备int值进行比较

答案 3 :(得分:1)

最后,我找到了以下解决方案。感谢您的提示。

public static OlDaysOfWeek AsDaysOfWeek(this DayOfWeek dayOfWeek)
{
    return (OlDaysOfWeek)(1 << (int)dayOfWeek);
}

要这样使用:

var day = DayOfWeek.Friday;
OlDaysOfWeek days = day.AsDaysOfWeek();

此外,这些是该方法在NUnit中的单元测试:

[TestCase(DayOfWeek.Monday, OlDaysOfWeek.olMonday)]
[TestCase(DayOfWeek.Tuesday, OlDaysOfWeek.olTuesday)]
[TestCase(DayOfWeek.Wednesday, OlDaysOfWeek.olWednesday)]
[TestCase(DayOfWeek.Thursday, OlDaysOfWeek.olThursday)]
[TestCase(DayOfWeek.Friday, OlDaysOfWeek.olFriday)]
[TestCase(DayOfWeek.Saturday, OlDaysOfWeek.olSaturday)]
[TestCase(DayOfWeek.Sunday, OlDaysOfWeek.olSunday)]
public void AsDaysOfWeek(DayOfWeek dayOfWeek, OlDaysOfWeek expectedResult)
{
    var result = dayOfWeek.AsDaysOfWeek();

    Assert.That(result, Is.EqualTo(expectedResult));
}