[英]UNITY C# - How can I get all the fields of the an instance of a class marked with my custom atribute(the fields)?
In Unity Ive got a object of a class with many fields.在 Unity 中,我得到了一个 object 的 class 有很多字段。 Some of them are marked with [CockpitControlled] attribute, which I defined as:
其中一些标有 [CockpitControlled] 属性,我将其定义为:
[AttributeUsage(AttributeTargets.Field)]
public class CockpitControlled : Attribute
{
}
In some other class I would to get a list of all those field as I would like to change them.在其他一些 class 中,我想获得所有这些字段的列表,因为我想更改它们。 Question is how?
问题是如何?
By reflection, you get the fields of a type and check if the attribute is present.通过反射,您可以获得一个类型的字段并检查该属性是否存在。
Example:例子:
[AttributeUsage(AttributeTargets.Field)]
public class CockpitControlled : Attribute
{
public int SomeValue { get; set; }
}
public class SomeData
{
private string _data1;
[CockpitControlled]
private string _data2;
private string _data3;
[CockpitControlled( SomeValue = 42)]
private string _data4;
}
static void Main(string[] args)
{
foreach(var field in typeof(SomeData).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
var att = field.GetCustomAttributes(typeof(CockpitControlled), true).FirstOrDefault() as CockpitControlled;
if(att == null)
{
Console.WriteLine($"The field {field.Name} isn't CockpitControlled");
}
else
{
Console.WriteLine($"The field {field.Name} is CockpitControlled with the value {att.SomeValue}");
}
}
}
Ouput:输出:
The field _data1 isn't CockpitControlled
The field _data2 is CockpitControlled with the value 0
The field _data3 isn't CockpitControlled
The field _data4 is CockpitControlled with the value 42
Edit:编辑:
This example set "bbb" in instance's fields that are CockpitControlled with the value "aaa":此示例在 CockpitControlled 的实例字段中设置“bbb”,值为“aaa”:
[AttributeUsage(AttributeTargets.Field)]
public class CockpitControlled : Attribute
{ }
public class SomeData
{
public string _data1;
[CockpitControlled]
public string _data2;
[CockpitControlled]
public string _data3;
}
static void Main()
{
// Create a instance
var datas = new SomeData { _data1 = "aaa", _data2 = "aaa", _data3 = "zzz", };
// For each field of the instance
foreach (var field in datas.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
// Check if the field is CockpitControlled
var att = field.GetCustomAttributes(typeof(CockpitControlled), true).FirstOrDefault() as CockpitControlled;
if (att != null)
{
// Get the value of the field
var curentValue = (string)field.GetValue(datas);
// If the value of the field equal "aaa"
if (curentValue == "aaa")
// Set "bbb"
field.SetValue(datas, "bbb");
}
}
Console.WriteLine(datas._data1);
Console.WriteLine(datas._data2);
Console.WriteLine(datas._data3);
}
Result:结果:
aaa
bbb
zzz
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.