繁体   English   中英

C#将字符串强制转换为类对象

[英]c# casting string to class object

我想从数据库中将字符串转换为类对象,而不必遍历每个可能的结果。

所以不

if(type.StartsWith("ContactPersonType")){//} else if(type.StartsWith("ContactPersonTitle")){//}

这就是我到目前为止

        private static T Create<T>(IDataRecord record)
    {
        var properties = typeof(T).GetProperties();
        var returnVal = Activator.CreateInstance(typeof(T));
        properties.ToList().ForEach(item =>
        {
            string type = item.GetMethod.ReturnParameter.ParameterType.Name;
            if (type.StartsWith("ContactPerson"))
            {
                Type t = Type.GetType(item.GetMethod.ReturnParameter.ParameterType.ToString());
                item.SetValue(returnVal, Convert.ChangeType(record[item.Name].ToString(), t));
            }
            else if (!type.StartsWith("ObservableCollection"))
            {
                item.SetValue(returnVal, Convert.ChangeType(record[item.Name].ToString(), item.PropertyType));
            }

        });
        return (T)returnVal;
    }

public class ContactPersonType
{
    private int _id;
    public int ID
    {
        get { return _id; }
        set { _id = value; }
    }

    private String _name;
    public String Name
    {
        get { return _name; }
        set { _name = value; }
    }
}

谢谢

当您希望将某个操作应用于不同的输入值时,请使用匿名集合。

foreach(var option in new[] {"ContactPerson", "ContactPersonTitle" }){
   if (type.StartsWith(option))
   {
        Type t = Type.GetType(item.GetMethod.ReturnParameter.ParameterType.ToString());
        item.SetValue(returnVal, Convert.ChangeType(record[item.Name].ToString(), t));
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM