我为我的应用程序发送的电子邮件设置了一组模板。模板中嵌入了与我的业务对象的属性相对应的代码。
还有比打电话更优雅的方式吗?
string.Replace("{!MyProperty!}", item.MyProperty.ToString()) 无数次?也许是XMLTransform,正则表达式,或者其他一些魔术?我使用的是C# 3.5。
发布于 2008-10-27 18:25:14
首先,当我这样做时,我使用StringBuilder.Replace(),因为我发现它的性能在处理3个或更多替换对象时要好得多。
当然,还有其他方法可以做到这一点,但我发现通常不值得花额外的精力去尝试其他项目。
我猜你可以使用反射来自动化替换,这可能是唯一“更好”的方法。
发布于 2008-10-27 19:42:38
public static string Translate(string pattern, object context)
{
return Regex.Replace(pattern, @"\{!(\w+)!}", match => {
string tag = match.Groups[1].Value;
if (context != null)
{
PropertyInfo prop = context.GetType().GetProperty(tag);
if (prop != null)
{
object value = prop.GetValue(context);
if (value != null)
{
return value.ToString();
}
}
}
return "";
});
}Translate("Hello {!User!}. Welcome to {!GroupName!}!", new {
User = "John",
GroupName = "The Community"
}); // -> "Hello John. Welcome to The Community!"发布于 2008-10-27 18:32:00
您可以使用regex来完成此操作,但是您的regex替换对于每个属性也是不同的。我会坚持使用string.Replace。
使用反射来检索属性并在循环中替换它:
foreach (string property in properties)
{
string.Replace("{!"+property+"!}",ReflectionHelper.GetStringValue(item,property));
}只需实现ReflectionHelper.GetStringValue方法并使用反射来检索item对象类型的所有属性。
https://stackoverflow.com/questions/240949
复制相似问题