通过与特定的属性字段进行遍历 [英] Iterating through fields with specific attribute

查看:220
本文介绍了通过与特定的属性字段进行遍历的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是pretty新在C#中的反映。我想创建,我可以用我的字段使用一个特定的属性,这样我就可以通过他们所有的检查,而不是每次都写这些检查每一个领域,他们是正确初始化。我认为这将是这个样子:

I'm pretty new to reflection in C#. I want to create a specific attribute that I can use with my fields, so I can go through them all and check that they are initialized properly, instead of writing these checks every time for every field. I think it would look something like this:

public abstract class BaseClass {

    public void Awake() {

        foreach(var s in GetAllFieldsWithAttribute("ShouldBeInitialized")) {

            if (!s) {

                Debug.LogWarning("Variable " + s.FieldName + " should be initialized!");
                enabled = false;

            }

        }

    }

}

public class ChildClass : BasicClass {

    [ShouldBeInitialized]
    public SomeClass someObject;

    [ShouldBeInitialized]
    public int? someInteger;

}

(您可能注意到,我打算用它Unity3d,但没有什么具体到Unity在这个问题上 - 或者至少,它似乎很给我)。这可能吗?

(You may notice that I intend to use it Unity3d, but there's nothing specific to Unity in this question — or at least, it seems so to me). Is this possible?

推荐答案

您可以用一个简单的前pression得到这样的:

You can get this with a simple expression:

private IEnumerable<FieldInfo> GetAllFieldsWithAttribute(Type attributeType)
{
    return this.GetType().GetFields().Where(
        f => f.GetCustomAttributes(attributeType, false).Any());
}

然后您的来电更改为:

Then change your call to:

foreach(var s in GetAllFieldsWithAttribute(typeof(ShouldBeInitializedAttribute)))

您可以通过使它的扩展方法上的键入这让整个应用的实用性

You can make this more useful throughout your app by making it an extension method on Type:

public static IEnumerable<FieldInfo> GetAllFieldsWithAttribute(this Type objectType, Type attributeType)
{
    return objectType.GetFields().Where(
        f => f.GetCustomAttributes(attributeType, false).Any());
}

您会叫这个为:

this.GetType().GetAllFieldsWithAttribute(typeof(ShouldBeInitializedAttribute))

修改:要获得私有字段,修改 GetFields()来:

Edit: To get private fields, change GetFields() to:

GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)

和让(你的循环内)类型:

And to get the type (inside your loop):

object o = s.GetValue(this);

这篇关于通过与特定的属性字段进行遍历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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