【发布时间】:2011-10-18 17:55:35
【问题描述】:
我需要找到数据库中每个字符串列的最大大小作为设计另一个数据库的信息之一。我对源数据库的唯一访问是通过 Web 服务。我可以为许多列中的每一个都做它以找到最大的大小,但我希望它是通用的,以便我以后可以使用它。
我写了这个非常简化的版本以使其易于理解。最后两行发明了语法,这是我需要帮助的地方。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class myClass
{
private string s;
public string S
{
get { return s; }
set { s = value; }
}
private int i;
public int I
{
get { return i; }
set { i = value; }
}
}
class Program
{
static void Main(string[] args)
{
Type myClassType = typeof(myClass);
System.Reflection.PropertyInfo[] propertyInfo = myClassType.GetProperties();
Dictionary<string, int> property = new Dictionary<string, int>();
foreach (System.Reflection.PropertyInfo info in propertyInfo)
if (info.PropertyType == typeof(System.String))
property.Add(info.Name, -1);
myClass[] myPa = new myClass[2];
myPa[0] = new myClass();
myPa[0].S = "1";
myPa[0].I = 0;
myPa[1] = new myClass();
myPa[1].S = "12";
myPa[1].I = 1;
这是我需要帮助的地方。我发明了c[pair.key]。如何引用我知道名称的属性?
foreach (myClass c in myPa)
foreach (KeyValuePair<string, int> pair in property)
if (c[pair.Key].Length > pair.Value)
property[pair.Key] = c[pair.Key].Length;
foreach (KeyValuePair<string, int> pair in property)
Console.WriteLine("Property: {0}, Biggest Size: {1}", pair.Key, pair.Value);
}
}
}
输出应该是:
Property: S Biggest Size: 2
【问题讨论】:
标签: c# reflection