从 c# 中的字符串绑定 class 属性

Bind class properties from string in c#

我有一个类似“dataSource=ReportDataSource;storedProcedure=GetUserEmails;tableName=Users”的字符串。 有没有办法从这种类型的字符串中绑定 class 属性。我有一个 class 包含所有 3 个属性 dataSource、storedProcedure 和 tableName。

尝试使用 linq 而不是循环,但暂时这应该可行:

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

和 class:

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

假设您的目标 class 看起来像这样:

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

这是一个简单的方法:

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

注意:如果你的字符串里面已经包含了\"——你需要转义它:

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

您可以在 Restester.

上观看现场演示