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
843 views
in Technique[技术] by (71.8m points)

c# - nameof with generic types

I am trying to get the name of a method on a generic interface. I would expect this to work as the type part would be a valid typeof:

//This does not compile
nameof(IGenericInterface<>.Method)

//This would compile
typeof(IGenericInterface<>)

I think this should be valid c#-6.0 or am I missing something or is there a better way to do this. I don't want to use a string for the Method name as if the method is renamed code would break without any build-time errors.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This is expected. According to the documentation, your expression is disallowed, because it refers to an unbound generic type:

Because the argument needs to be an expression syntactically, there are many things disallowed that are not useful to list. The following are worth mentioning that produce errors: predefined types (for example, int or void), nullable types (Point?), array types (Customer[,]), pointer types (Buffer*), qualified alias (A::B), and unbound generic types (Dictionary<,>), preprocessing symbols (DEBUG), and labels (loop:).

You can work around this limitation by supplying a generic parameter:

nameof(IGenericInterface<object>.Method)

Note: I think Microsoft should tweak nameof feature to allow references to methods of unbound generic types.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

56.8k users

...