Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

.net - Why does nameof return only last name?

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

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))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...