是方法命名为IL标准化财产getter / setter方法​​? [英] Is the method naming for property getters/setters standardized in IL?

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

问题描述

我有以下两种方法,如果他们是适当的,我想知道:

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. 他们总是用开始得到_ 集_ ,而普通方法可以与这些前缀开头。

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

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

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