简体   繁体   中英

C# string interpolation within a static context

I'm currently trying to generate a class as with some properties, which I've to set before compiling the code. 的类,在编译代码之前必须设置这些属性。

Let's take a look at my code, I'm using a static string :

    public class NewHumanSource
    {
            static readonly string template =
                "internal class {ClassName} : IHuman " + 
                "{ " +
                     // bunch of private fields here;
                     "private int age; " + Environment.NewLine +

                     "public int Age" + Environment.NewLine +
                     "{" + Environment.NewLine +
                          "get =>" + $"{int.Parse("{Age}")}" + ";" + Environment.NewLine +
                          "set" + Environment.NewLine +
                          "{" + Environment.NewLine +
                               "age= value;" + Environment.NewLine +
                               "OnPropertyChanged(nameof(age));" +Environment.NewLine +      
                          "}" + Environment.NewLine +
                     "}" + Environment.NewLine + Environment.NewLine +

                      // Other properties and members
                ";"

The static member that is used to set values to the source code template :

 public static string GetSourceCode(IHuman newHuman, string className)
 {
     code = code.Replace("{ClassName}", className.ToLowerInvariant().Replace(" ", ""));
     code = code.Replace("{Age}", newHuman.Age.ToString()); //Age is an integer.
     //...
 }

Then called from an external class :

 var code = NewHumanSource.GetSourceCode(newHuman, className);

Exception is thrown at that line. The static method won't even load :

System.TypeInitializationException: 'The type initializer for 'DynamicCompilerTest.Classes.DynamicCompiler.NewHumanSource' threw an exception.'

InnerException  {"Input string was not in a correct format."}   System.Exception {System.FormatException}

It'd would work just fine is all properties were strings but this string interpolation raises the exception :

 "get =>" + $"{int.Parse("{Age}")}" + ";" +

Any idea of how I should handle non string type ? I Need to handle built-in type like DateTime and such. Or is there even a more elegant way to create a class as text with properties values ? I might get ride of the formatting.

Thanks a lot for your help / tips !

This will not work this way. int.Parse("{Age}") will be evaluated during type initialization, and thus it cannnot use Age . Based on your code, I believe you just need to replace it with return age .

You can also benefit from using multiline string literal:

static readonly string template =
    @"internal class {ClassName} : IHuman 
      {
          // bunch of private fields here
          private int age = {Age};

          public int Age
          {
              get { return age; }
              set
              {
                  age = value;
                  OnPropertyChanged(nameof(Age));
              }
          }

          // Other properties and members
      }";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM