F# 联合成员的 Enum.GetName 等效项是什么?
我想要为 F# 受歧视的联合成员获取相当于 Enum.GetName
的内容。 调用 ToString()
会得到 TypeName+MemberName,这并不是我想要的。 当然,我可以对它进行子串化,但是它安全吗? 或者也许有更好的方法?
I want to get the equivalent of Enum.GetName
for an F# discriminated union member. Calling ToString()
gives me TypeName+MemberName, which isn't exactly what I want. I could substring it, of course, but is it safe? Or perhaps there's a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要使用 Microsoft.FSharp.Reflection 命名空间中的类,以便:
You need to use the classes in the
Microsoft.FSharp.Reflection
namespace so:@DanielAsher 的答案有效,但为了使其更优雅(并且更快?因为其中一种方法缺乏反射),我会这样做:(
受到 这个和这个。)
@DanielAsher's answer works, but to make it more elegant (and fast? because of the lack of reflection for one of the methods), I would do it this way:
(Inspired by this and this.)
该答案为最佳答案提供了更多信息和解决方案。
我刚刚遇到了一个案例,最佳答案不起作用。 问题是该值位于接口后面,然后我有时会得到案例名称(咖啡或茶),但大多数情况下只有类型名称(饮料)。 我不明白为什么。 我使用的是.NET 5.0。
我将函数更改为此,然后它在我的接口 DU 上按预期工作,始终为我提供案例名称。
我知道这与此处的其他答案类似,但这不是成员函数,因此我想应该适用于任何 DU,无论是否位于接口后面。 我还没有测试过如果在非 DU 类型上使用会发生什么。
This answer supplies additional information and solutions to the top answer.
I just now had a case where the top answer did not work. The problem was that the value was behind an interface, and then I would sometimes get the case name (Coffee or Tea), but mostly only the type name (Beverage). I don't understand why. I'm on .NET 5.0.
I changed the function to this, and then it worked as expected on my interfaced DU, always giving me the case name.
I am aware that this is similar to other answers here, but this is not a member function, and so I guess should work on any DU, whether behind interfaces or not. I haven't tested what happens if used on a non-DU type.
我想提出一些更简洁的建议:
当 union case 很简单时,
GetName()
可能会带来与ToString()
相同的结果:但是,如果 union case 更花哨,会有区别:。
I would like to propose something even more concise:
When union case is simple,
GetName()
may bring the same asToString()
:However, if union case is fancier, there will be a difference:.