我想要做的是这样的事情:我有枚举标记值的枚举。
public static class EnumExtension
{
public static bool IsSet<T>( this T input, T matchTo )
where T:enum //the constraint I want that doesn't exist in C#3
{
return (input & matchTo) != 0;
}
}
那么我就可以做到:
MyEnum tester = MyEnum.FlagA | MyEnum.FlagB
if( tester.IsSet( MyEnum.FlagA ) )
//act on flag a
不幸的是,C#是通用的,其中约束没有枚举限制,只有类和结构。 C#没有将枚举看作结构(即使它们是值类型),所以我不能像这样添加扩展类型。
有没有人知道解决方法?
答案 0 :(得分:47)
编辑:现在在UnconstrainedMelody版本0.0.0.2中有效。
(根据我的blog post about enum constraints的要求。为了获得独立的答案,我在下面列出了基本事实。)
最好的解决方案是等我将其包含在UnconstrainedMelody 1 中。这是一个库,它采用带有“假”约束的C#代码,如
where T : struct, IEnumConstraint
并将其变为
where T : struct, System.Enum
通过后期制作步骤。
写IsSet
不应该太难......虽然基于Int64
和UInt64
的标志可能是最棘手的部分。 (我闻到了一些辅助方法,基本上允许我处理任何标记枚举,好像它的基本类型为UInt64
。)
如果你打电话
,你想要的行为是什么?tester.IsSet(MyFlags.A | MyFlags.C)
?它应该检查 all 是否设置了指定的标志?那是我的期望。
我会在今晚回家的路上尝试这样做...我希望快速了解有用的枚举方法,以便快速将库升级到可用的标准,然后放松一下。
编辑:顺便说一句,我不确定IsSet
是一个名字。选项:
欢迎思考。我相信在任何事情发生之前都会有一段时间......
1 或者将其作为补丁提交,当然......
答案 1 :(得分:16)
Darren,如果类型是特定的枚举,它会工作 - 对于工作的一般枚举,你必须将它们转换为int(或者更可能是uint)来进行布尔数学运算:
public static bool IsSet( this Enum input, Enum matchTo )
{
return ( Convert.ToUInt32( input ) & Convert.ToUInt32( matchTo ) ) != 0;
}
答案 2 :(得分:9)
实际上,这可能是一个丑陋的伎俩。 但是,它不能用于扩展方法。
public abstract class Enums<Temp> where Temp : class {
public static TEnum Parse<TEnum>(string name) where TEnum : struct, Temp {
return (TEnum)Enum.Parse(typeof(TEnum), name);
}
}
public abstract class Enums : Enums<Enum> { }
Enums.IsSet<DateTimeKind>("Local")
如果您愿意,可以将Enums<Temp>
私有构造函数和公共嵌套抽象继承类Temp
作为Enum
,以防止非枚举的继承版本。
答案 3 :(得分:8)
您可以使用IL Weaving和ExtraConstraints
来实现这一目标允许您编写此代码
public class Sample
{
public void MethodWithDelegateConstraint<[DelegateConstraint] T> ()
{
}
public void MethodWithEnumConstraint<[EnumConstraint] T>()
{
}
}
汇编了什么
public class Sample
{
public void MethodWithDelegateConstraint<T>() where T: Delegate
{
}
public void MethodWithEnumConstraint<T>() where T: struct, Enum
{
}
}
答案 4 :(得分:4)
这不能回答原始问题,但现在在.NET 4中有一个名为Enum.HasFlag的方法可以完成您在示例中要执行的操作
答案 5 :(得分:3)
我这样做的方法是放置一个struct约束,然后在运行时检查T是一个枚举。这并没有完全消除这个问题,但确实有所减少
答案 6 :(得分:2)
从C#7.3开始,您可以对泛型类型使用Enum约束:
public static TEnum Parse<TEnum>(string value) where TEnum : Enum
{
return (TEnum) Enum.Parse(typeof(TEnum), value);
}
如果要使用Nullable枚举,则必须保留orginial struct约束:
public static TEnum? TryParse<TEnum>(string value) where TEnum : struct, Enum
{
if( Enum.TryParse(value, out TEnum res) )
return res;
else
return null;
}
答案 7 :(得分:1)
使用原始代码,在方法内部,您还可以使用反射来测试T是枚举:
public static class EnumExtension
{
public static bool IsSet<T>( this T input, T matchTo )
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("Must be an enum", "input");
}
return (input & matchTo) != 0;
}
}
答案 8 :(得分:1)
这里有一些我刚刚做过的代码似乎可以像你想要的那样工作,而不必做任何太疯狂的事情。它不仅限于设置为Flags的枚举,但如果需要,可以随时进行检查。
public static class EnumExtensions
{
public static bool ContainsFlag(this Enum source, Enum flag)
{
var sourceValue = ToUInt64(source);
var flagValue = ToUInt64(flag);
return (sourceValue & flagValue) == flagValue;
}
public static bool ContainsAnyFlag(this Enum source, params Enum[] flags)
{
var sourceValue = ToUInt64(source);
foreach (var flag in flags)
{
var flagValue = ToUInt64(flag);
if ((sourceValue & flagValue) == flagValue)
{
return true;
}
}
return false;
}
// found in the Enum class as an internal method
private static ulong ToUInt64(object value)
{
switch (Convert.GetTypeCode(value))
{
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
return (ulong)Convert.ToInt64(value, CultureInfo.InvariantCulture);
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return Convert.ToUInt64(value, CultureInfo.InvariantCulture);
}
throw new InvalidOperationException("Unknown enum type.");
}
}
答案 9 :(得分:0)
我只是想将Enum添加为通用约束。
虽然这仅仅是针对使用ExtraConstraints
的小辅助方法,但对我来说有点太多开销。
我决定只创建一个struct
约束并为IsEnum
添加运行时检查。为了将变量从T转换为Enum,我首先将其转换为对象。
public static Converter<T, string> CreateConverter<T>() where T : struct
{
if (!typeof(T).IsEnum) throw new ArgumentException("Given Type is not an Enum");
return new Converter<T, string>(x => ((Enum)(object)x).GetEnumDescription());
}
答案 10 :(得分:0)
如果有人需要通用的IsSet(在飞行中创建的框可以改进),或者字符串到Enum onfly转换(使用下面的EnumConstraint):
public class TestClass
{ }
public struct TestStruct
{ }
public enum TestEnum
{
e1,
e2,
e3
}
public static class TestEnumConstraintExtenssion
{
public static bool IsSet<TEnum>(this TEnum _this, TEnum flag)
where TEnum : struct
{
return (((uint)Convert.ChangeType(_this, typeof(uint))) & ((uint)Convert.ChangeType(flag, typeof(uint)))) == ((uint)Convert.ChangeType(flag, typeof(uint)));
}
//public static TestClass ToTestClass(this string _this)
//{
// // #generates compile error (so no missuse)
// return EnumConstraint.TryParse<TestClass>(_this);
//}
//public static TestStruct ToTestStruct(this string _this)
//{
// // #generates compile error (so no missuse)
// return EnumConstraint.TryParse<TestStruct>(_this);
//}
public static TestEnum ToTestEnum(this string _this)
{
// #enum type works just fine (coding constraint to Enum type)
return EnumConstraint.TryParse<TestEnum>(_this);
}
public static void TestAll()
{
TestEnum t1 = "e3".ToTestEnum();
TestEnum t2 = "e2".ToTestEnum();
TestEnum t3 = "non existing".ToTestEnum(); // default(TestEnum) for non existing
bool b1 = t3.IsSet(TestEnum.e1); // you can ommit type
bool b2 = t3.IsSet<TestEnum>(TestEnum.e2); // you can specify explicite type
TestStruct t;
// #generates compile error (so no missuse)
//bool b3 = t.IsSet<TestEnum>(TestEnum.e1);
}
}
如果某人仍然需要热点来创建枚举编码约束:
using System;
/// <summary>
/// would be same as EnumConstraint_T<Enum>Parse<EnumType>("Normal"),
/// but writen like this it abuses constrain inheritence on System.Enum.
/// </summary>
public class EnumConstraint : EnumConstraint_T<Enum>
{
}
/// <summary>
/// provides ability to constrain TEnum to System.Enum abusing constrain inheritence
/// </summary>
/// <typeparam name="TClass">should be System.Enum</typeparam>
public abstract class EnumConstraint_T<TClass>
where TClass : class
{
public static TEnum Parse<TEnum>(string value)
where TEnum : TClass
{
return (TEnum)Enum.Parse(typeof(TEnum), value);
}
public static bool TryParse<TEnum>(string value, out TEnum evalue)
where TEnum : struct, TClass // struct is required to ignore non nullable type error
{
evalue = default(TEnum);
return Enum.TryParse<TEnum>(value, out evalue);
}
public static TEnum TryParse<TEnum>(string value, TEnum defaultValue = default(TEnum))
where TEnum : struct, TClass // struct is required to ignore non nullable type error
{
Enum.TryParse<TEnum>(value, out defaultValue);
return defaultValue;
}
public static TEnum Parse<TEnum>(string value, TEnum defaultValue = default(TEnum))
where TEnum : struct, TClass // struct is required to ignore non nullable type error
{
TEnum result;
if (Enum.TryParse<TEnum>(value, out result))
return result;
return defaultValue;
}
public static TEnum Parse<TEnum>(ushort value)
{
return (TEnum)(object)value;
}
public static sbyte to_i1<TEnum>(TEnum value)
{
return (sbyte)(object)Convert.ChangeType(value, typeof(sbyte));
}
public static byte to_u1<TEnum>(TEnum value)
{
return (byte)(object)Convert.ChangeType(value, typeof(byte));
}
public static short to_i2<TEnum>(TEnum value)
{
return (short)(object)Convert.ChangeType(value, typeof(short));
}
public static ushort to_u2<TEnum>(TEnum value)
{
return (ushort)(object)Convert.ChangeType(value, typeof(ushort));
}
public static int to_i4<TEnum>(TEnum value)
{
return (int)(object)Convert.ChangeType(value, typeof(int));
}
public static uint to_u4<TEnum>(TEnum value)
{
return (uint)(object)Convert.ChangeType(value, typeof(uint));
}
}
希望这有助于某人。