首先,请原谅我这个问题是否对网站上的其他信息有所帮助。我浏览了其他有关反思的文章,但就我在做什么似乎似乎没有任何意义。
想法是将一个方法传递给一个类,然后遍历该对象的属性并将其值分配给一个返回值。该返回值稍后将用于动态创建SQL语句。我已经使用PropertyInfo创建了循环,并且能够基于switch语句来判断属性的类型。问题是,一旦我在特定情况下使用该属性,就很难确定如何将特定的属性值分配给列表,以便稍后返回。这是我的代码,在此先感谢您的帮助。
public List<string> BuildParametersFromObject(clsBook oBook, clsStudent oStud)
{
List<string> lstRetVal = new List<string>();
string sTemp = "";
string sPropType = "";
int ii;
if (oBook == null)
{
PropertyInfo[] ObjProperties = typeof(clsStudent).GetProperties();
foreach (PropertyInfo StudProp in ObjProperties)
{
ii = 0;
sPropType = Convert.ToString(StudProp.PropertyType);
switch (sPropType)
{
case "System.String":
lstRetVal.Add(StudProp.GetValue(clsStudent, null));
break;
case "System.Int32":
break;
case "System.Decimal":
break;
case "System.Boolean":
break;
case "System.DateTime":
break;
}
}
}
return lstRetVal;
}
您的代码无法编译,因为
StudProp.GetValue(clsStudent, null)
要求它的第一个参数是对象,而您要给该方法最确定的是类符号。
其次,我试图了解您打算对两个参数执行的操作:
clsBook oBook
clsStudent oStud
从您在那里写的内容我知道,如果oBook
不为null,则可以将结果添加到返回列表中。我现在就保留它。
第二大问号是是否需要该oStud
参数。
说你解决编制问题,而你的代码不编译。如果您尝试完全删除参数,即
public List<string> BuildParametersFromObject(clsBook oBook, clsStudent oStud)
变成
public List<string> BuildParametersFromObject(clsBook oBook)
您会注意到您的方法仍然可以编译,因此您没有使用oStud
。
您正在枚举 clsStudent
如果您不确定我在说什么,则可以执行以下操作:
修改方式
// prepare your little filter
private static readonly Type[] allowedTypes = new Type[] {
typeof(bool), typeof(string), typeof(int),
typeof(decimal), typeof(DateTime)
};
public List<string> BuildParametersFromObject(clsBook oBook, clsStudent oStud)
{
List<string> lstRetVal = new List<string>();
string sTemp = "";
string sPropType = "";
int ii;
if (oBook == null)
{
PropertyInfo[] ObjProperties = typeof(clsStudent).GetProperties();
foreach (PropertyInfo StudProp in ObjProperties)
{
// if the property's type is not one of the 5 magnificence
// simply jump to the next cycle of the foreach loop
if (!allowedTypes.Contains(StudProp.PropertyType))
continue;
object pureValue = StudProp.GetValue(oStud);
// what you were using is not ok: StudProp.GetValue(clsStudent)
// because you're trying to retrieve the value of a property
// defined by the clsStudent class
// and in the process you also need to point out an instance
// of that particular class, but instead of doing that
// you were pointing out an instance of Type i.e. clsStudent itself
string stringValue = pureValue + "";
// simply concatenate the pureValue with a blank string
// (allowing imminent nulls to be displayed as empty strings instead of crashing your thread with NullReferenceException)
lstRetVal.Add(stringValue);
// just add your stringified value to the list
}
}
return lstRetVal;
}
解释
我所做的是,将您的显式过滤(使用switch)修改为原始数组(您希望在添加结果中支持的类型的列表),并且由此我也删除了不必要且完全困难的部分保持类型的“按名称比较”。比较类型和它们本身的类型要干净得多。世界上可能有RunninThruLife,但只有一个是您。
最大的错误是,您不是从clsStudent实例获取属性的值,而是从clsStudent本身(这是一个类)获取属性的值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句