I have an exception type in my project which I throw when the result of a method that I invoke is null
, or is not what is expected. I pass the method name as an argument to that exception (for simplicity, I have omitted any other arguments I provide to it in the sample below):
var result = someObject.SomeMethod();
if (result == null)
{
throw new MethodResultException(nameof(someObject.SomeMethod));
}
This works fine in most cases, except when SomeMethod
is an extension method. In that case, I get the following error:
CS8093: Extension method groups are not allowed as an argument to 'nameof'.
Is there any other way that I can get the name of an extension method, as a string, in a similar way to how I can get the name of a 'regular' method?
- I don't always have access to the source of the extension method, so I can't put this logic in the method itself, otherwise I would use MethodBase.GetCurrentMethod.
- I also would like to avoid having to hardcode strings with the method names in my code, in case they get changed. If I want to rename a variable or method using Visual Studio's rename feature, any references with
nameof
will be changed as well.
Aucun commentaire:
Enregistrer un commentaire