为什么nameof只返回姓氏? [英] Why does nameof return only last name?

查看:98
本文介绍了为什么nameof只返回姓氏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

nameof(order.User.Age)仅返回 Age 而不是 order。 User.Age

以更严格的方式执行此操作的原因是什么?
如果只需要姓氏,我们可以做类似

What is the reason to do it in more restricted way? If we want only last name we could do something like

public static GetLastName(this string x) { 
    return string.Split(x, '.').Last();
}

nameof(order.User.Age).GetLastName()

使用一个运算符,我们可以同时获得 Age order.User.Age 。但是使用当前的实现,我们只能获得 Age 。这个决定背后有逻辑吗?例如,这种行为对于MVC绑定是必需的

And with one operator we could get both, Age and order.User.Age. But with current implementation we can only get Age. Is there some logic behind this decision? For example, such behavior is necessary for MVC binding

Html.TextBox(nameof(order.User.Age))


推荐答案

请注意,如果您需要/想要全名,可以这样做:

Note that if you need/want the "full" name, you could do this:

$"{nameof(order)}.{nameof(User)}.{nameof(Age)}".GetLastName();

,只要所有这些名称都在当前范围内

显然,在这种情况下,它并不是真正有用的(名称在Razor调用中不会在范围内),但是如果您需要,例如,调用 Type.GetType()之类的类型的完整名称空间限定名称。

Obviously in this case it's not really all that helpful (the names won't be in scope in the Razor call), but it might be if you needed, for example, the full namespace qualified name of a type for a call to Type.GetType() or something.

如果名称不在范围内,您仍然可以做些笨拙的操作:

If the names are not in scope, you could still do the somewhat more clunky:

$"{nameof(order)}.{nameof(order.User)}.{nameof(order.User.Age)}".GetLastName();

-尽管机会至少是其中之一(除非 User.Age 是静态属性)。

-- although chances are at least one of those should be in scope (unless User.Age is a static property).

这篇关于为什么nameof只返回姓氏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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