追踪方法上的特性!

public static T GetMethodAttr<T>(bool whole = true) where T : Attribute
        {
            T res = null;
            StackTrace st = new StackTrace(true);
            for (int i = 0 ; i < st.FrameCount ; i++)
            {
                StackFrame sf = st.GetFrame(i);
                var attrs = sf.GetMethod().GetCustomAttributes(typeof(T), false);
                if (attrs.Length > 0)
                {
                    res = attrs[0] as T;
                    if (!whole) return res;
                }
            }
            return res;
        }

说明:whole = true 追踪最外层的!!

posted @ 2019-07-04 19:09  zwsu  阅读(162)  评论(0编辑  收藏  举报