简体   繁体   English

C# 如何从基类中的派生类获取特定类型的所有字段?

[英]C# How do I get all the fields of a specific type from a derived class within the base class?

I have a class that looks like this:我有一个看起来像这样的课程:

public abstract class NetBehaviour
{
    void setSyncFloat (SyncFloat[] values)
    {
        // Find all SyncFloat fields in the child 
        // class (the one that derived this class).

    }
}

How do I go about finding all the fields of a specific type in a class that derived from this class within this very class?我如何在这个类中从这个类派生的类中查找特定类型的所有字段? It seems a bit tricky and I'm guessing I'll need reflections.这似乎有点棘手,我猜我需要反思。 Could anyone help me out?有人可以帮我吗?

public abstract class NetBehaviour
{
    void setSyncFloat (SyncFloat[] values)
    {
        // Find all SyncFloat fields in the child 
        // class (the one that derived this class).
        var fields = GetType()
            .GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
            .Where(fi => fi.FieldType == typeof(SyncFloat));
    }
}

BindingFlags have been included because I assume you want private fields. BindingFlags已包含在内,因为我假设您需要私有字段。

Note that GetType() will get the runtime type ie the subclass type.请注意, GetType()将获取运行时类型,即子类类型。

You are on the right track.你走在正确的轨道上。
Gladly this in you class will also be of the derived type, enabling you to do this.GetType() to receive the explicit most derived Type of the object.很高兴this在你的类中也将是派生类型,使你能够执行this.GetType()来接收对象的显式最派生Type
You can then use Type.GetFields() to receive an array of all fields of that type, that you can iterate.然后,您可以使用Type.GetFields()接收该类型的所有字段的数组,您可以对其进行迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM