C# 如何使方法适用于任何枚举
我有以下代码,其中ApplicationType是一个枚举。我在许多其他枚举上都有相同的重复代码(除了参数类型之外的所有代码)。整合此代码的最佳方法是什么C# 如何使方法适用于任何枚举,c#,enums,C#,Enums,我有以下代码,其中ApplicationType是一个枚举。我在许多其他枚举上都有相同的重复代码(除了参数类型之外的所有代码)。整合此代码的最佳方法是什么 private static string GetSelected(ApplicationType type_, ApplicationType checkedType_) { if (type_ == checkedType_) { return " selected ";
private static string GetSelected(ApplicationType type_, ApplicationType checkedType_)
{
if (type_ == checkedType_)
{
return " selected ";
}
else
{
return "";
}
}
从臀部开始射击,沿着
private static string GetSelected<T>(T type_, T checkedType_) where T : System.Enum{
//As before
}
虽然这在类型安全方面没有什么帮助,但是可以传入两种不同的枚举类型
您可能会在运行时失败:
private static String GetSelected(Enum type_, Enum checkedType_){
if(type_.GetType() != checkedType.GetType()) throw new Exception();
//As above
}
要获得编译时安全性,可以使用泛型约束,但由于不能使用枚举类,因此无法限制所有内容:
private static String GetSelected<T>(T type_, T checkedType_) where T : IComparable, IFormattable, IConvertible{
if(!(first is Enum)) throw new Exception();
//As above
}
私有静态字符串GetSelected(T type,T checkedType),其中T:IComparable,IFormattable,IConvertible{
如果(!(第一个是Enum))抛出新异常();
//如上
}
上述方法将确保只传递相同类型的枚举(如果传入两个不同的枚举,则会出现类型推断错误),但在传递满足T上约束的非枚举时,将进行编译
不幸的是,对于这个问题似乎没有很好的解决方案。在编译时通过泛型约束很难做到这一点,因为
enum
实际上是int
。您需要在运行时限制这些值。在emum上是否相等?简单地说:
public static string GetSelected<T>(T x, T y) {
return EqualityComparer<T>.Default.Equals(x,y) ? " selected " : "";
}
这适合你的需要吗
private static string GetSelected<T>(T type_, T checkedType_)
where T: struct
{
if(type_.Equals(checkedType_))
return " selected ";
return "";
}
私有静态字符串GetSelected(T类型,T检查类型)
其中T:struct
{
如果(类型等于(选中类型))
返回“已选择”;
返回“”;
}
约束不能是特殊类“System.Enum”,您需要使用关键字“struct”,因为枚举不起作用。您可以在运行时执行进一步的类型检查,以确保它实际上是一个枚举。已更新我的答案,使其不会非常非常非常错误。很抱歉。实际上,C#enum通常是一个
int
。Whups,我一直在研究的最新项目将enum映射到数据库中的一个字节-混乱。我会更新答案。谢谢
using System;
using System.Collections.Generic;
static class Program {
static void Main() {
ApplicationType value = ApplicationType.B;
Console.WriteLine("A: " + GetSelected(value, ApplicationType.A));
Console.WriteLine("B: " + GetSelected(value, ApplicationType.B));
Console.WriteLine("C: " + GetSelected(value, ApplicationType.C));
}
private static string GetSelected<T>(T x, T y) {
return EqualityComparer<T>.Default.Equals(x, y) ? " selected " : "";
}
enum ApplicationType { A, B, C }
}
private static string GetSelected<T>(T type_, T checkedType_)
where T: struct
{
if(type_.Equals(checkedType_))
return " selected ";
return "";
}