If you want to generate a string, you can use Linqto list properties:
MyClass test = new MyClass {
FirstName = "John",
LastName = "Smith",
};
String result = "My Name is " + String.Join(" ", test
.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(property => property.CanRead)
.Select(property => property.GetValue(test)));
Console.Write(result);
In case you want to replace a string (formatting type), regular expressions may be your choice for parsing a string:
String original = "My Name is @MyClass.FirstName @MyClass.LastName";
String pattern = "@[A-Za-z0-9\\.]+";
String result = Regex.Replace(original, pattern, (MatchEvaluator) ((match) =>
test
.GetType()
.GetProperty(match.Value.Substring(match.Value.LastIndexOf('.') + 1))
.GetValue(test)
.ToString()
));
Console.Write(result);
, , instance (i. e. not static), (test ):
.GetValue(test)
@MyClass , :
test.GetType()
: , null
String result = Regex.Replace(original, pattern, (MatchEvaluator) ((match) => {
Object v = test
.GetType()
.GetProperty(match.Value.Substring(match.Value.LastIndexOf('.') + 1))
.GetValue(test);
return v == null ? "NULL" : v.ToString();
}));