use*_*899 2 c# arrays getter properties
我有几个 get 属性,我希望它们能够像函数数组一样循环。我希望能够做这样的事情
public int prop1 { get; }
public string prop2 { get; }
public int[] prop3 { get; }
public int prop4 { get; }
public string prop5 { get; }
public string prop6 { get; }
Func<var> myProperties = { prop1, prop2, prop3, prop4, prop5, prop6 };
ArrayList myList = new ArrayList();
foreach( var p in myProperties)
{
myList.Add(p);
}
Run Code Online (Sandbox Code Playgroud)
这段代码非常糟糕,但我认为它传达了我想要做的事情的想法。有谁知道我怎么能做到这一点?
您可以使用反射来访问您的类型中的属性:
class MyType
{
public int prop1 { get; }
public string prop2 { get; }
public int[] prop3 { get; }
public int prop4 { get; }
public string prop5 { get; }
public string prop6 { get; }
public List<string> GetAllPropertyValues()
{
List<string> values = new List<string>();
foreach (var pi in typeof(MyType).GetProperties())
{
values.Add(pi.GetValue(this, null).ToString());
}
return values;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,反射很慢,如果有更好的方法,则不应使用它。例如,当您知道只有 6 个属性时,只需逐个检查它们。