Why does nameof return only last name?

前端 未结 5 914
南笙
南笙 2020-12-16 09:45

nameof(order.User.Age) return only Age instead of order.User.Age

What is the reason to do it in more restricted way? If we wan

5条回答
  •  轮回少年
    2020-12-16 10:15

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

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

    as long as all of these names are in the current scope.

    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();
    

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

提交回复
热议问题