Is the naming method for getters / seters properties standardized in IL?

I have the following two methods that interest me if they are suitable:

public bool IsGetter(MethodInfo method) { return method.IsSpecialName && method.Name.StartsWith("get_", StringComparison.Ordinal); } public bool IsSetter(MethodInfo method) { return method.IsSpecialName && method.Name.StartsWith("set_", StringComparison.Ordinal); } 

While this code works, I hope to avoid the part that checks StartsWith and gets a naming convention programmatically. Basically, are there any .NET 4.5 classes that can see if MethodInfo is an getter / setter attribute?

+8
c # properties naming-conventions
source share
2 answers

The property method has three additional characteristics compared to the conventional method:

  • They always start with get_ or set_ , while a regular CAN method can start with these prefixes.
  • The MethodInfo.IsSpecialName property is MethodInfo.IsSpecialName to true.
  • MethodInfo has a custom attribute System.Runtime.CompilerServices.CompilerGeneratedAttribute .

You can check 1, combined with option 2 or 3. Since prefixes are standard, you should not worry about checking on it.

Another method is to list all the properties and map the methods, which will be much slower:

 public bool IsGetter(MethodInfo method) { if (!method.IsSpecialName) return false; // Easy and fast way out. return method.DeclaringType .GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) .Any(p => p.GetGetMethod() == method); } 
+13
source share

You can try the following:

 public bool IsGetter(MethodInfo method) { return method.DeclaringType.GetProperties(). Any(propInfo => propInfo.GetMethod == method); } 

You can specify binding flags for GetProperties

+1
source share

All Articles