gpt4 book ai didi

C# 绑定(bind)对象到字符串

转载 作者:太空宇宙 更新时间:2023-11-03 22:47:50 24 4
gpt4 key购买 nike

我想将动态对象绑定(bind)到字符串,例如将字符串中的 instance.field 替换为实例的实际值。

请参阅下面的代码以了解:

String body = "My Name is: model.Name";
Model model = new Model();
model.Name = "Mohammed";
String result = ReplaceMethod(body,model);
// result is, My Name is: Mohammed

注意:我想在具有太多字段的大字符串值中使用此过程。谢谢。

最佳答案

我不会在像“model.Name”这样的字符串中使用前缀,我会立即使用{Name}。我们需要的是找到所有这些,Regex 可以帮助我们。

试试这个方法,查看评论:

class Program
{
static void Main(string[] args)
{
String body = "My Name is: {Name} {LastName}";
Model model = new Model();
model.Name = "Mohammed";
model.LastName = "LastName";
String result = ReplaceMethod(body, model);
}

private static string ReplaceMethod(string body, Model model)
{
// can't name property starting with numbers,
// but they are possible
Regex findProperties = new Regex(@"{([a-zA-Z]+[0-9]*)}");

// order by desc, since I want to replace all substrings correctly
// after I replace one part length of string is changed
// and all characters at Right are moved forward or back
var res = findProperties.Matches(body)
.Cast<Match>()
.OrderByDescending(i => i.Index);

foreach (Match item in res)
{
// get full substring with pattern "{Name}"
var allGroup = item.Groups[0];

//get first group this is only field name there
var foundPropGrRoup = item.Groups[1];
var propName = foundPropGrRoup.Value;

object value = string.Empty;

try
{
// use reflection to get property
// Note: if you need to use fields use GetField
var prop = typeof(Model).GetProperty(propName);

if (prop != null)
{
value = prop.GetValue(model, null);
}
}
catch (Exception ex)
{
//TODO Logging here
}

// remove substring with pattern
// use remove instead of replace, since
// you may have several the same string
// and insert what required
body = body.Remove(allGroup.Index, allGroup.Length)
.Insert(allGroup.Index, value.ToString());

}

return body;
}

public class Model
{
public string Name { get; set; }
public string LastName { get; set; }
}
}

关于C# 绑定(bind)对象到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49082476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com