C#编译时才生成字符串?

问题描述 投票:0回答:1

我想在编译时调用

System.DateTime.Now.ToString()
并将返回值存储在 const 字符串中,该字符串不会被
DateTime.Now
更新。

有没有简单的方法可以做到这一点?网上有很多关于程序集的主题,但我并没有尝试设置程序集版本,因此这似乎不是正确的方法。

c# string datetime compilation visual-studio-2017
1个回答
0
投票

关于我的评论,当然还有另一种方法。通过使用T4。只需将 T4 模板添加到您的项目...并将其更改为使用 UTC

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ output extension=".cs" #>
// <auto-generated>
//     This code was generated by a tool.
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
namespace YourStuff
{
    internal static class CompileTime
    {
        internal static string Stamp
        {
            get
            {
<#
        var stamp = System.DateTime.Now.ToString("yyyy.MM.dd HH:mm");
#>
                return "<#=stamp#>";
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.