1

是否有可能将System.DayOfWeek的值直接转换为Microsoft.Office.Interop.Outlook.OlDaysOfWeek的值。就像是:

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

4 回答 4

2

你可以试试这个:

var olDay = (OlDaysOfWeek) Enum.Parse(typeof(OlDaysOfWeek), $"ol{systemDay}");
于 2019-04-16T11:00:14.630 回答
2

要在不使用字符串操作的情况下执行此操作,这里有一个选项:

public OlDaysOfWeek ConvertToDaysOfWeek(DayOfWeek day)
{
    return (OlDaysOfWeek)Math.Pow(2, (int)day); 
}
于 2019-04-16T11:05:35.037 回答
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());
}

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

于 2019-04-16T11:05:00.003 回答
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));
}
于 2019-04-16T11:08:48.073 回答