Use nameof for a member of a common class without specifying type arguments

class Foo<T> { public T Bar() { /* ... */ } } 

I want to pass the name of the bar to Type.GetMethod(string) . I can do this as someType.GetMethod(nameof(Foo<int>.Bar)) , but that int is completely arbitrary here; is there any way i can omit? Unfortunately, nameof(Foo<>.Bar) does not work.

This is not so important in this case of toys, but if there are several type parameters, and especially if they have where bindings that can be associated with them, they can be called.

+5
source share
1 answer

The nameof documentation says that what you want to do is forbidden, unfortunately:

Since the argument must be a syntax expression, there are many things that cannot be listed. The following are worth mentioning that they produce errors: predefined types (for example, int or void ), types with a null value ( Point? ), Array types ( Customer[,] ), pointer types ( Buffer* ), qualified alias ( A::B ) and unrelated common types ( Dictionary<,> ) , preprocessing characters ( DEBUG ), and labels ( loop: .

The best you can probably do is to specify Bar in the interface and use nameof(IFoo.Bar) . Of course, this is not an option if Bar contains in its signature something related to T (as in this particular case).


Another option is to create an interface where each T is replaced by object . Then a particular type explicitly implements the interface, also implementing common versions of the same methods.

This has several disadvantages:

  • Enlarged API surface
  • More complex and error-prone refactoring
  • Loss of compilation type security, as the caller can use the object interface.

It is probably impractical to use nameof , but in some cases this strategy makes sense for other reasons. In such cases, the possibility of using nameof will be just a convenient bonus.

+3
source

Source: https://habr.com/ru/post/1236373/


All Articles