Is the method naming for property getters/setters standardized in IL?

こ雲淡風輕ζ 提交于 2019-11-29 09:56:41
Martin Mulder

A property method has three extra characteristics, compared with a normal method:

  1. They always start with get_ or set_, while a normal method CAN start with those prefixes.
  2. The property MethodInfo.IsSpecialName is set to true.
  3. The MethodInfo has a custom attribute System.Runtime.CompilerServices.CompilerGeneratedAttribute.

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

The other method is to enumerate through all properties and match 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);
}

You could try the following:

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

You can optionally specify the binding flags for GetProperties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!