简体   繁体   中英

Bind class properties from string in c#

I have a string like "dataSource=ReportDataSource;storedProcedure=GetUserEmails;tableName=Users". Is there a way to bind the class properties from this type of string. I have a class with all 3 properties dataSource,storedProcedure and tableName.

Try to use linq instead of the loops, but temporarily this should work:

string s = "dataSource=ReportDataSource;storedProcedure=GetUserEmails;tableName=Users";
var split1 = s.Split(';');
var props = new Dictionary<string, string>();
foreach(var ss in split1)
{
    var splitProperty = ss.Split('=');
    props.Add(splitProperty[0], splitProperty[1]);
}
var newDbCon = new dbCon();
var classType = typeof(dbCon);
foreach(var p in props)
{
    classType.GetProperty(p.Key).SetValue(newDbCon, p.Value);
}

And the class:

class dbCon
    {
        public string dataSource { get; set; }
        public string storedProcedure { get; set; }
        public string tableName { get; set; }
    }

Assuming your target class looks like this:

    public class Target
    {
        public string DataSource {get;set;}
        
        public string StoredProcedure {get;set;}
        
        public string TableName {get;set;}
    }

Here's a simple way to do it:

// That's your source string
var source = "dataSource=ReportDataSource;storedProcedure=GetUserEmails;tableName=Users";

// Using a couple of replaces and add `{"` at the start and `"}` at the end, 
// convert your source string to json:
var json = "{\"" + source.Replace("=", "\":\"").Replace(";", "\",\"") + "\"}";

// Deserialize
var target = JsonConvert.DeserializeObject<Target>(json);

Note: If your string already contains \" inside - you need to escape it:

var json = "{\"" + source.Replace("\"", "\\\"").Replace("=", "\":\"").Replace(";", "\",\"") + "\"}";

You can see a live demo on Restester.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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