如何过滤作为类事件的底层实现的 FieldInfo?

发布于 2024-09-02 11:40:15 字数 88 浏览 4 评论 0原文

我想获取类的所有字段,而不获取类事件的底层实现。 type.GetFields(BindingFlags...) 返回事件字段的裸体委托。有谁知道如何过滤掉它们?

I want to get all the fields of a class without getting the underlying implementations of the class event.
type.GetFields(BindingFlags...) returns the nuderlying delegate for event fields. Does anyone knows how to filter them out ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉城メ夜风 2024-09-09 11:40:15

.NET 中的事件生成一个与事件具有相同类型的字段。此外,它们还生成两个方法(adder 和remover,它们与带有前缀“add_”和“remove_”的字段同名)。

为了过滤事件支持字段,您可以删除与事件同名的字段。您可以确保不会定义与事件同名的字段,因为如果使用相同名称定义另一个成员,编译器将导致编译失败。

例如:

public IEnumerable<FieldInfo> FilterBackingEventFields(Type type)
{
    List<string> eventNames = type
        .GetEvents().Select(eventInfo => eventInfo.Name).ToList();

    FieldInfo[] fieldInfos = type
        .GetFields(BindingFlags.NonPublic | 
                   BindingFlags.Public | 
                   BindingFlags.Instance);

    return fieldInfos.Where(fieldInfo => !eventNames.Contains(fieldInfo.Name));
}

用法示例:

public class ClassWithEventAndField
{
    public event EventHandler MyEvent;
    public int MyField;
}

[Test]
public void TestFieldsFilter()
{
    IEnumerable<FieldInfo> fields = 
        FilterBackingEventFields(typeof(ClassWithEventAndField));

    FieldInfo expectedField = typeof(ClassWithEventAndField).GetField("MyField");
    Assert.That(fields, Is.EquivalentTo(new[] { expectedField }));
}

编辑: 添加了对 VB 和 C# 的支持

此代码将适用于自动生成的事件(自定义加法器或删除器将破坏代码)。这也是一个有风险的代码,它对 adder 方法的生成和编译方式做出了一些假设。我将此代码发布为“学术”信息,我不会在生产代码中使用它。

public IEnumerable<FieldInfo> FilterBackingEventFields(Type type)
{
    List<int> backingFieldsTokens = type
        .GetEvents().Select(eventInfo => MetadataToken(eventInfo)).ToList();

    FieldInfo[] fieldInfos = type
        .GetFields(BindingFlags.NonPublic | 
                   BindingFlags.Public | 
                   BindingFlags.Instance);

    return fieldInfos
     .Where(fieldInfo => !backingFieldsTokens.Contains(fieldInfo.MetadataToken));
}

private static int MetadataToken(EventInfo eventInfo)
{
    MethodInfo adderMethod = eventInfo.GetAddMethod();
    int fieldToken =
        adderMethod.GetMethodBody().GetILAsByteArray()[3] |
        adderMethod.GetMethodBody().GetILAsByteArray()[4] << 8 |
        adderMethod.GetMethodBody().GetILAsByteArray()[5] << 16 |
        adderMethod.GetMethodBody().GetILAsByteArray()[6] << 24;

    return fieldToken;
}

这里所做的假设是,adder 方法主体中的字节 3-6 是事件的后备字段的标记。我真的希望有人能为这个问题发布一个优雅且安全的解决方案:)

Events in .NET generate a field with the same and type as the event. In addition they generates two methods (adder and remover, which have the same name as the field with prefixes 'add_' and 'remove_').

In order to filter event backing fields you can remove fields with same name as events. You can be sure no field will be defined with same name as event since the compiler will fail the compilation if another member is defined with the same name.

For example:

public IEnumerable<FieldInfo> FilterBackingEventFields(Type type)
{
    List<string> eventNames = type
        .GetEvents().Select(eventInfo => eventInfo.Name).ToList();

    FieldInfo[] fieldInfos = type
        .GetFields(BindingFlags.NonPublic | 
                   BindingFlags.Public | 
                   BindingFlags.Instance);

    return fieldInfos.Where(fieldInfo => !eventNames.Contains(fieldInfo.Name));
}

Usage example:

public class ClassWithEventAndField
{
    public event EventHandler MyEvent;
    public int MyField;
}

[Test]
public void TestFieldsFilter()
{
    IEnumerable<FieldInfo> fields = 
        FilterBackingEventFields(typeof(ClassWithEventAndField));

    FieldInfo expectedField = typeof(ClassWithEventAndField).GetField("MyField");
    Assert.That(fields, Is.EquivalentTo(new[] { expectedField }));
}

EDIT: added support to work with VB and C#

This code will work on auto generated events (custom adder or remover will break the code). This is also a risky code, it makes some assumptions on the way adder method is generated and compiles. I am posting this code as "Academic" information, I wouldn't use it in production code.

public IEnumerable<FieldInfo> FilterBackingEventFields(Type type)
{
    List<int> backingFieldsTokens = type
        .GetEvents().Select(eventInfo => MetadataToken(eventInfo)).ToList();

    FieldInfo[] fieldInfos = type
        .GetFields(BindingFlags.NonPublic | 
                   BindingFlags.Public | 
                   BindingFlags.Instance);

    return fieldInfos
     .Where(fieldInfo => !backingFieldsTokens.Contains(fieldInfo.MetadataToken));
}

private static int MetadataToken(EventInfo eventInfo)
{
    MethodInfo adderMethod = eventInfo.GetAddMethod();
    int fieldToken =
        adderMethod.GetMethodBody().GetILAsByteArray()[3] |
        adderMethod.GetMethodBody().GetILAsByteArray()[4] << 8 |
        adderMethod.GetMethodBody().GetILAsByteArray()[5] << 16 |
        adderMethod.GetMethodBody().GetILAsByteArray()[6] << 24;

    return fieldToken;
}

The assumption made here is that the bytes 3-6 in the adder method body are the token of the backing field of the event. I really hope someone will post an elegant and safe solution to this problem :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文