我正在尝试使用反射设置属性值,如下所示。我想知道是否有任何通用的方法来查找属性类型,而不是以下面的方式执行它。
string currentlblTxt;
string currentTxt;
Assembly assembly = Assembly.GetAssembly(typeof(myAdapter));
myAdapter currentEventObject = (myAdapter)assembly.CreateInstance(myClassName);
int m = k;
for (m = 1; m < k; m++)
{
currentlblTxt = ((Label)FindControl("lblB" + m.ToString())).Text;
currentTxt = ((TextBox)FindControl("txtB" + m.ToString())).Text;
if (!string.IsNullOrEmpty(currentTxt))
{
if (currentEventObject.GetType().GetProperty(currentlblTxt) != null)
{
if ((currentEventObject.GetType().GetProperty(currentlblTxt).PropertyType.Equals(typeof(System.Boolean))))
{
currentEventObject.GetType().GetProperty(currentlblTxt).SetValue(currentEventObject, Convert.ToBoolean(currentTxt), null);
}
else if ((currentEventObject.GetType().GetProperty(currentlblTxt).PropertyType.Equals(typeof(System.DateTime))))
{
currentEventObject.GetType().GetProperty(currentlblTxt).SetValue(currentEventObject, Convert.ToDateTime(currentTxt), null);
}
else if ((currentEventObject.GetType().GetProperty(currentlblTxt).PropertyType.Equals(typeof(System.Guid))))
{
Guid val = new Guid(currentTxt);
currentEventObject.GetType().GetProperty(currentlblTxt).SetValue(currentEventObject, val, null);
}
else
{
currentEventObject.GetType().GetProperty(currentlblTxt).SetValue(currentEventObject, currentTxt, null);
}
}
}
}
请建议。
由于
答案 0 :(得分:0)
TypeDescriptor 是针对您似乎正在做的事情而制作的。
var desciptor = TypeDescriptor.GetConverter(propertyType);
var isValid = converter.IsValid(value);
if (isValid)
{
var convertedValue = converter.ConvertFromString(value));
}