属性 getter/setter 的方法命名是否在 IL 中标准化? [英] Is the method naming for property getters/setters standardized in IL?

查看:21
本文介绍了属性 getter/setter 的方法命名是否在 IL 中标准化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两种方法,我想知道它们是否合适:

I have the following two methods that I am wondering if they are appropriate:

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);
}

<小时>

虽然此代码有效,但我希望避免检查 StartsWith 并以编程方式获取命名约定的部分.基本上,是否有任何 .NET 4.5 类能够查看 MethodInfo 是否为属性 getter/setter?


While this code works, I'm hoping to avoid the portion that checks the StartsWith and programmatically get the naming convention. Basically, are there any .NET 4.5 classes that are able to see if the MethodInfo is a property getter/setter?

推荐答案

与普通方法相比,属性方法具有三个额外的特性:

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

  1. 它们总是以 get_set_ 开头,而普通方法可以以这些前缀开头.
  2. 属性 MethodInfo.IsSpecialName 设置为 true.
  3. MethodInfo 有一个自定义属性 System.Runtime.CompilerServices.CompilerGeneratedAttribute.
  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.

您可以检查 1,结合选项 2 或 3.由于前缀是标准的,您不必担心检查它.

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);
}

这篇关于属性 getter/setter 的方法命名是否在 IL 中标准化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆