Doing this at runtime without using reflection would mean that a generic solution is not possible. You would have to write different method for each class you want to support. A very simple version:
static string SomeFunction(string format, MyClass instance)
{
return format.Replace("{CutoutKind}", instance.CutoutKind.ToString())
.Replace("{EdgeKind}", instance.EdgeKind.ToString())
.Replace("{EdgeKind}", instance.MaterialKind.ToString());
}
Or a slightly more sophisticated version:
Dictionary<string, Func<MyClass, string>> propertyGetters =
new Dictionary<string, Func<MyClass, string>>
{
{ "CutoutKind", x => x.CutoutKind.ToString() }
{ "EdgeKind", x => x.EdgeKind.ToString() }
{ "EdgeKind", x => x.MaterialKind.ToString() }
};
static string SomeFunction(string format, MyClass instance)
{
return Regex.Replace(@"\{(\w+)\}",
m => propertyGetters.HasKey(m.Groups[1].Value)
? propertyGetters[m.Groups[1].Value](instance)
: m.Value;
}
But if you decide you don't want to have to write this kind of method for each class, here's a simple generic version using reflection:
static string SomeFunction<T>(string format, T instance)
{
var propertyInfos = typeof(T)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.ToDictionary(p => p.Name);
return Regex.Replace(@"\{(\w+)\}",
m => propertyInfos.HasKey(m.Groups[1].Value)
? propertyInfos[m.Groups[1].Value].GetValue(instance, null)
: m.Value;
}
FormattableString
, you can muck around with it manually. i.e.FormattableString x = $"...";
.