如何使方法适用于任何枚举
我有以下代码,其中 ApplicationType 是一个枚举。我在许多其他枚举上都有相同的重复代码(除了参数类型之外的所有内容)。合并此代码的最佳方法是什么?
private static string GetSelected(ApplicationType type_, ApplicationType checkedType_)
{
if (type_ == checkedType_)
{
return " selected ";
}
else
{
return "";
}
}
I have the following code, where ApplicationType is an enum. I have the same repeated code (everything except the parameter types) on many other enums. Whats the best way to consolidate this code?
private static string GetSelected(ApplicationType type_, ApplicationType checkedType_)
{
if (type_ == checkedType_)
{
return " selected ";
}
else
{
return "";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从臀部开枪,类似于......显然这是非法的。
为了简单地减少重复,您可以将 T 替换为 Enum,
尽管这不会给您带来太多类型安全性,因为可以传入两种不同的枚举类型。
可能会在运行时失败:
您 一些编译时安全性,您可以使用通用约束,但由于您不能使用 Enum 类,您将无法限制所有内容:
上面的内容将确保您只传递相同类型的枚举(您将得到一个如果传入两个不同的枚举,则会出现类型推断错误),但当传递满足 T 约束的非枚举时,将会编译。
不幸的是,这个问题似乎没有一个很好的解决方案。
Shooting from the hip, something along the lines of...Apparently that's illegal.
To simply cut down on repetition, you could just replace T with Enum thusly,
Though this doesn't get you much in the way of type safety, as two different enumeration types could be passed in.
You could instead fail at runtime:
To get some compile time safety you could use a generic constraint, though since you can't using the Enum class you won't be able to restrict everything:
The above will make sure you only pass Enums of the same type (you'll get a type inference error if you pass in two different Enums) but will compile when non-Enum's that meet the constraints on T are passed.
There doesn't seem to be a great solution to this problem out there, unfortunately.
为了 emum 上的平等?简单地说:
您可以将
where T : struct
添加到顶行,但不需要这样做。对于包括演示的完整示例:
For equality on an emum? Simply:
You could add
where T : struct
to the top line, but there isn't a need to do that.For a full example including demo:
这适合您的需求吗?
Is this appropriate for your needs?
在编译时通过通用约束很难做到这一点,因为
enum
实际上是一个int
。您需要在运行时限制这些值。It's hard to do this through a generic constraint at compile time because an
enum
is really anint
. You'll need to restrict the values at runtime.