【问题标题】:How to list all class members (including inherited) tha are marked with protobuf .net ProtoMember attribute?如何列出标有 protobuf .net ProtoMember 属性的所有类成员(包括继承的)?
【发布时间】:2012-12-10 09:46:31
【问题描述】:

有一个类类型(例如从C继承的D,从B继承的D)如何按从上父到下子(B)的顺序列出所有标有protobuf .net ProtoMember属性的类成员(包括继承的)成员、C 成员、D 成员)?

【问题讨论】:

  • 这很简单:答案是“无”。 [ProtoMember] 有一个 [AttributeUsage] 声明,将使用限制为属性和字段,而不是方法。因此,在 any 级别上用[ProtoMember] 标记的方法恰好为零。但是,如果您实际上是指“成员”,那么:反射是您的朋友。

标签: c# .net inheritance reflection protobuf-net


【解决方案1】:

通常答案是使用GetFields()GetProperties()Attribute.IsDefined 进行反射检查。但是,在这种情况下,最好询问 protobuf-net 模型 认为存在什么:

using ProtoBuf;
using ProtoBuf.Meta;
using System;
[ProtoContract, ProtoInclude(5, typeof(Bar))]
public class Foo
{
    [ProtoMember(1)]
    public int X { get; set; }
}
[ProtoContract]
public class Bar : Foo
{
    [ProtoMember(1)]
    public string Y { get; set; }
}
static class Program {
    static void Main() {
        var metaType = RuntimeTypeModel.Default[typeof(Bar)];
        do {
            Console.WriteLine(metaType.Type.FullName);
            foreach(var member in metaType.GetFields())
            {
                Console.WriteLine("> {0}, {1}, field {2}",
                    member.Member.Name, member.MemberType.Name,
                    member.FieldNumber);
            }
        } while ((metaType = metaType.BaseType) != null);
    }
}

这样做的好处是它甚至可以用于自定义配置(属性不是配置 protobuf-net 的唯一机制)

【讨论】:

    猜你喜欢
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    相关资源
    最近更新 更多