F#中有C#的nameof(..)的等效项吗? [英] Is there an equivalent of C#'s nameof(..) in F#?

查看:84
本文介绍了F#中有C#的nameof(..)的等效项吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几行代码想从C#移植到F#:

I have the following lines of code I want to port from C# to F#:

private const string TypeName = nameof(MyClass);
private const string MemberName = nameof(MyClass.MyMember);

然后TypeName的值是"MyClass",然后MemberName的值是"MyMember".我必须用F#写什么?

The value of TypeName then is "MyClass" and the value of MemberName then is "MyMember". What do I have to write in F#?

推荐答案

如注释中所述,正在进行适当的nameof运算符.

As mentioned in the comments, a proper nameof operator is work in progress.

同时,您可以使用F#引号(类似于C#表达式树)来实现类似的功能-有点丑陋并且需要一定的纪律(您需要将实际的成员访问权限放在引号中),但至少检查成员是否存在并防止输入错误:

In the meantime, you can use F# quotations (similar to C# expression trees) to implement similar functionality - it is a bit uglier and requires some discipline (you need to put actual member access in the quotation), but it at least checks that the member exists and prevents typos:

open Microsoft.FSharp.Quotations

let nameof (q:Expr<_>) = 
  match q with 
  | Patterns.Let(_, _, DerivedPatterns.Lambdas(_, Patterns.Call(_, mi, _))) -> mi.Name
  | Patterns.PropertyGet(_, mi, _) -> mi.Name
  | DerivedPatterns.Lambdas(_, Patterns.Call(_, mi, _)) -> mi.Name
  | _ -> failwith "Unexpected format"

let any<'R> : 'R = failwith "!"

any定义只是一个通用值,可用于引用实例成员:

The any definition is just a generic value that you can use to refer to instance members:

nameof <@ any<System.Random>.Next @>
nameof <@ System.Char.IsControl @>

这篇关于F#中有C#的nameof(..)的等效项吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆