c#泛型类限制为枚举的子集

时间:2020-07-31 21:44:45

标签: c# generics

我正在建立一个通用类来表示测量数量及其度量单位。度量单位是通用变量,我定义了几个单位类型枚举。如您所见,单位是在构造函数中设置的,并使用反射在整个单位集中找到正确的属性并将其设置为该属性。如果它从未在单元集中找到匹配的属性,则将引发异常。有没有一种方法可以将TEnum进一步限制为我打算枚举的子集?

namespace measureClasses
{
    public class MeasureClass<TEnum> where TEnum : Enum
    {
        public TEnum MeasureUnit { get; private set; }
        public double MeasureValue { get; private set; }

        public MeasureClass(double measureValue = 0d)
        {
            List<PropertyInfo> properties = MainWindow.CurrentUnitSystem.GetType().GetProperties().ToList();
            bool unitSet = false;

            foreach (PropertyInfo property in properties)
            {
                if (property.PropertyType == typeof(TEnum))
                {
                    MeasureUnit = (TEnum)property.GetValue(MainWindow.CurrentUnitSystem);
                    unitSet = true;

                    break;
                }
            }

            if (!unitSet)
                throw new InvalidOperationException("Invalid unit type");

            MeasureValue = measureValue;
        }
    }
}

0 个答案:

没有答案