簡體   English   中英

靜態上下文中的C#字符串插值

[英]C# string interpolation within a static context

我目前正在嘗試生成具有某些屬性的字符串形式的類,在編譯代碼之前必須設置這些屬性。

讓我們看一下我的代碼,我使用的是靜態字符串:

    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
                ";"

用於為源代碼模板設置值的靜態成員:

 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.
     //...
 }

然后從外部類調用:

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

在該行拋出異常。 靜態方法甚至不會加載:

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}

如果所有屬性都是字符串,那會很好用,但是此字符串插值會引發異常:

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

關於如何處理非字符串類型的任何想法嗎? 我需要處理諸如DateTime之類的內置類型。 還是有一種更優雅的方法來創建一個具有屬性值的文本類? 我可能會喜歡格式化。

非常感謝您的幫助/提示!

這樣將無法正常工作。 int.Parse("{Age}")將在類型初始化期間求值,因此不能使用Age 根據您的代碼,我相信您只需要將其替換為return age

您還可以從使用多行字符串文字中受益:

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
      }";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM