![](/img/trans.png)
[英]C# How do I get all the fields of a specific type from a derived class within the base class?
[英]UNITY C# - How can I get all the fields of the an instance of a class marked with my custom atribute(the fields)?
在 Unity 中,我得到了一個 object 的 class 有很多字段。 其中一些標有 [CockpitControlled] 屬性,我將其定義為:
[AttributeUsage(AttributeTargets.Field)]
public class CockpitControlled : Attribute
{
}
在其他一些 class 中,我想獲得所有這些字段的列表,因為我想更改它們。 問題是如何?
通過反射,您可以獲得一個類型的字段並檢查該屬性是否存在。
例子:
[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}");
}
}
}
輸出:
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
編輯:
此示例在 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);
}
結果:
aaa
bbb
zzz
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.