反射:在运行时将事件字段与委托类型的字段区分开 [英] Reflection: Distinguishing event-field from field of delegate type on runtime

查看:78
本文介绍了反射:在运行时将事件字段与委托类型的字段区分开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主要问题是: 是否有可能在反思中将某种委托类型的字段与事件用作存储字段的字段区分开? 问题归结为:FieldInfo类是否包含有关它是否属于事件的信息(如storagefield)?我找不到任何可以说明的属性,也找不到custum属性.

The main question I have is: Is it possible in reflection to distinguish a field of some delegate type from a field which is used by an event as storagefield? That comes down to the question: does the FieldInfo class contain information about whether it belongs to an event, as storagefield ? I can't find any properties which might tell, nor custum attributes.

在下面的代码中,SomeField和SomeEvent的两个FieldInfo的相关属性都相同.因此,我不知道如何根据它们是否为事件存储字段来对FieldInfo进行排序.

In the code below, the relevant properties of both FieldInfos of SomeField and SomeEvent are identical. So I don't know how to sort FieldInfos based on whether they are eventstoragefields or not.

using System;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace Test
{
    class Program
    {
        public Action SomeField;
        public event Action SomeEvent;
        static void Main(string[] args)
        {
            FieldInfo[] fields = typeof(Program).GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
            foreach (FieldInfo fi in fields)
               Console.WriteLine(string.Format("FieldName: {0}, Accessibility: {1}, Has Attributes: {2}.", fi.Name, fi.Attributes,
                    fi.GetCustomAttributes(true).Length != 0));
            Console.ReadLine();
        }
    }
}

一种解决方案是搜索具有完全相同名称的eventInfo,但是我不知道这是否万无一失,坦率地说,我对这种解决方案不满意.必须有更直接的方法.

One solution is to search for an eventInfo with exactly the same name, but I don't know whether that is foolproof and frankly, I would not be satisfied with that solution. There must be a more direct way.

推荐答案

简短的回答:不,没有愚蠢的方法可以做到这一点.甚至不必为事件提供后备委托字段.如果有的话,它们之间的元数据也没有任何联系.

Short answer: No, there's no fool proof way to do it. There doesn't even have to be a backing delegate field for an event. And if there is, there's no connection in metadata between them.

这篇关于反射:在运行时将事件字段与委托类型的字段区分开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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