C # Reflection: replace all occurrence of property with value in text

I have a class like

public class MyClass {

  public string FirstName {get; set;}
  public string LastName {get; set;}

}

The fact is that I have text text, for example

string str = "My Name is @MyClass.FirstName @MyClass.LastName";

I want to replace @ MyClass.FirstName and @ MyClass.LastName with reflection values ​​that are assigned to the FirstName and LastName objects in the class.

Any help please?

+4
source share
3 answers

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)  // Not necessary
    .Select(property => property.GetValue(test)));

  // My Name is John Smith
  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() // providing that null can't be returned
  ));

  // My Name is John Smith
  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(); 
 }));
+5

, , , string.Format. . , :

public void Main()
{
    string str = "My Name is @MyClass.FirstName @MyClass.LastName";
    var me = new MyClass { FirstName = "foo", LastName = "bar" };
    ReflectionReplace(str, me);
}

public string ReflectionReplace<T>(string template, T obj)
{    
    foreach (var property in typeof(T).GetProperties())
    {
        var stringToReplace = "@" + typeof(T).Name + "." + property.Name;
        var value = property.GetValue(obj);
        if (value == null) value = "";
        template = template.Replace(stringToReplace, value.ToString());
    }
    return template;
}

, , . .

+3

Reflection, , .

MyClass obj = new MyClass() { FirstName = "Praveen", LaseName = "Paulose" };

        string str = "My Name is @MyClass.FirstName @MyClass.LastName";

        string firstName = (string)obj.GetType().GetProperty("FirstName").GetValue(obj, null);
        string lastName = (string)obj.GetType().GetProperty("LaseName").GetValue(obj, null);

        str = str.Replace("@MyClass.FirstName", firstName);
        str = str.Replace("@MyClass.LastName", lastName);

        Console.WriteLine(str);

GetProperty, , GetValue

UPDATE

,

. .. @MyClass.Property. , Type.GetType , , , . .

+2

Source: https://habr.com/ru/post/1615599/


All Articles