开发者

Generic way of Checking Property Type using reflection

开发者 https://www.devze.com 2023-02-19 14:04 出处:网络
I am trying to set property value using reflection as below. I wanted to know if there is any generic way of finding the property type instead of doing it int he below way开发者_高级运维.

I am trying to set property value using reflection as below. I wanted to know if there is any generic way of finding the property type instead of doing it int he below way开发者_高级运维.

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);
            }
    }
    }  

}

Please Suggest.

Thanks


TypeDescriptor was made for what you seem to be doing.

var desciptor = TypeDescriptor.GetConverter(propertyType);
var isValid = converter.IsValid(value);

if (isValid)
{
    var convertedValue = converter.ConvertFromString(value));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消