我有一个包含30个属性的对象,我知道这些属性的名称。这些属性被称为"ValueX“(1-30),其中X是一个数字。
如何在循环中调用value1 - value30?
发布于 2009-11-05 01:10:12
下面将把所有属性/值选择到一个匿名类型的IEnumerable中,其中包含您感兴趣的属性的名称/值对。它假设属性是公共的,并且您是从对象的方法访问的。如果属性不是公共的,那么您需要使用BindingFlags来表明您想要非公共的属性。如果来自对象外部,请将this替换为感兴趣的对象。
var properties = this.GetType()
.GetProperties()
.Where( p => p.Name.StartsWith("Value") )
.Select( p => new {
Name = p.Name,
Value = p.GetValue( this, null )
}); 发布于 2009-11-05 01:06:15
使用反射。
public static string PrintObjectProperties(this object obj)
{
try
{
System.Text.StringBuilder sb = new StringBuilder();
Type t = obj.GetType();
System.Reflection.PropertyInfo[] properties = t.GetProperties();
sb.AppendFormat("Type: '{0}'", t.Name);
foreach (var item in properties)
{
object objValue = item.GetValue(obj, null);
sb.AppendFormat("|{0}: '{1}'", item.Name, (objValue == null ? "NULL" : objValue));
}
return sb.ToString();
}
catch
{
return obj.ToString();
}
}发布于 2009-11-05 01:07:15
您可以考虑改用集合或自定义索引器。
public object this[int index]
{
get
{
...
}
set
{
...
}
}然后你可以说;
var q = new YourClass();
q[1] = ...
q[2] = ...
...
q[30] = ...https://stackoverflow.com/questions/1675238
复制相似问题