Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用C中的常量替换硬编码字符串#_C#_Constants - Fatal编程技术网

C# 用C中的常量替换硬编码字符串#

C# 用C中的常量替换硬编码字符串#,c#,constants,C#,Constants,我试图获取.cs文件中的所有硬编码字符串,并从常量文件加载它 比如说 string capital="Washington"; 应加载为 string capital=Constants.capital; 这将添加到Constants.cs中 public final const capital="Washington"; 我需要一个java/C代码段来完成这个任务。我不能使用任何第三方工具。有什么帮助吗 编辑: 在阅读了评论和答案后,我感觉自己不太清楚。我只想找到一种方法来替换所有硬编码

我试图获取.cs文件中的所有硬编码字符串,并从常量文件加载它

比如说

string capital="Washington";
应加载为

string capital=Constants.capital;
这将添加到Constants.cs中

public final const capital="Washington";
我需要一个java/C代码段来完成这个任务。我不能使用任何第三方工具。有什么帮助吗

编辑:


在阅读了评论和答案后,我感觉自己不太清楚。我只想找到一种方法来替换所有硬编码的常量,这些常量将包含“”,然后将其撕掉并替换为常量。并在Constants.cs中添加该属性。这也可以是一个简单的文本处理。

有什么原因不能将这些属性放入静态类或应用程序中的文件中?你可以把常数放在任何地方,只要它们的作用域正确,你就可以从任何地方访问它们

public const string capital = "Washington";
若const在静态类中不起作用,那个么它将是

public static readonly string capital = "Washington";

如果确实要按照您描述的方式执行,请使用streamreader读取文件,按\r\n拆分,检查第一件事是否为“字符串”,然后对该字符串元素执行所有替换操作。。。
确保每次更改该字符串声明时,都会将必要行添加到另一个文件中。

您可以为常量创建一个类项目,或者如果您有一个助手类项目,则可以为常量添加一个新类(
constants.cs

您现在可以使用以下功能:

string capital = Constants.CAPITAL_Washington;

您不妨将常量命名得非常具体。

我不知道是否有这样的代码可用,但我提供了一些如何实现它的指南

  • 您可以编写宏/独立应用程序(我认为宏是更好的选择)
  • 分析当前文档或项目/解决方案中的所有文件
  • 编写一个正则表达式来查找字符串(XAML中的字符串如何?)。类似于[string]([a-z a-Z0-9])[“]([a-z a-Z0-9])[“][;]——这是无效的,我只是提供讨论
  • 从代码中提取常量
  • 检查静态类中是否已经存在类似的字符串
  • 如果未找到,请在静态类中插入新条目
  • 用变量名替换字符串
  • 转到步骤2

  • 以下几点提示可以帮助您开始学习:

    假设字符串处理器函数名为ProcessString

    1) 将Constants.cs与ProcessStrings函数包含在同一个项目中,以便使用重构代码对其进行编译

    2) 反思您的Constants类,构建一个常量名称的语言字符串字典,如:

    Dictionary<String, String> constantList = new Dictionary<String, String>();
    FieldInfo[] fields = typeof(Constants).GetFields(BindingFlags.Static | BindingFlags.Public);
    String constantValue;
    
    foreach (FieldInfo field in fields)
    {
        if (field.FieldType == typeof(String))
        {                    
            constantValue = (string)field.GetValue(null);             
            constantList.Add(constantValue, field.Name);
        }
    }
    
    6) 现在,匹配行中任何带引号的字符串,然后检查每个匹配项并检查其是否存在一些条件。如果需要,可以删除其中一些条件

    MatchCollection mC = Regex.Matches(lines[idx], "@?\"([^\"]+)\"");
    
    foreach (Match m in mC)
    {                           
    
        if (            
            // Detect format insertion markers that are on their own and ignore them, 
            !Regex.IsMatch(m.Value, @"""\s*\{\d(:\d+)?\}\s*""") &&
            //or check for strings of single character length that are not proper characters (-, /, etc)
            !Regex.IsMatch(m.Value, @"""\s*\\?[^\w]\s*""") &&
            //check for digit only strings, allowing for decimal places and an optional percentage or multiplier indicator
            !Regex.IsMatch(m.Value, @"""[\d.]+[%|x]?""") &&
            //check for array indexers
            !(m.Index <= lines[idx].Length && lines[idx][m.Index - 1] == '[' && lines[idx][m.Index + m.Length] == ']')  &&          
            )
        {
            String toCheck = m.Groups[1].Value;
    
            //look up the string we found in our list of constants
            if (constantList.ContainsKey(toCheck))
            {
                String replaceString;
    
                replaceString = "Constants." + constants[toCheck];              
    
                //replace the line in the file
                lines[idx] = lines[idx].Replace("\"" + m.Groups[1].Value + "\"", replaceString);
            }
            else
            {
    
                //See Point 8....
    
            }
        }
    
    MatchCollection mC=Regex.Matches(行[idx],“@?\”([^\“]+)\”);
    foreach(在mC中匹配m)
    {                           
    如果(
    //检测单独的格式插入标记并忽略它们,
    !Regex.IsMatch(m.Value,@“”“\s*\{\d(:\d+?\}\s*”)&&
    //或检查单字符长度的字符串是否为不正确的字符(-、等)
    !Regex.IsMatch(m.Value,@““\s*\\?[^\w]\s*”“”)&&
    //检查仅限数字的字符串,允许小数点和可选的百分比或乘数指示器
    !Regex.IsMatch(m.Value,@“”[\d.]+[%|x]?“”)&&
    //检查数组索引器
    
    !(m.Index您不能创建资源文件吗?不,我必须从另一个cs文件加载它。可怜的开发人员不是设计师:)我认为OP想要自动化这种重构的过程,并且正在寻找一些代码来完成这项工作。我认为他/她只需要自己完成这项工作。太棒了,你太棒了。只有一票,我喜欢有一票的机器人:)
    //check if the line is a comment or xml comment
    if (Regex.IsMatch(lines[idx], @"^\s*//")) 
        continue;
    
    //check if the entry is an attribute
    if (Regex.IsMatch(lines[idx], @"^\s*\["))
        continue;
    
    //check if the line is part of a block comment (assuming a * at the start of the line)
    if (Regex.IsMatch(lines[idx], @"^\s*(/\*+|\*+)"))
        continue;
    
    //check if the line has been marked as ignored 
    //(this is something handy I use to mark a string to be ignored for any reason, just put //IgnoreString at the end of the line)
    if (Regex.IsMatch(lines[idx], @"//\s*IgnoreString\s*$")) 
        continue;
    
    MatchCollection mC = Regex.Matches(lines[idx], "@?\"([^\"]+)\"");
    
    foreach (Match m in mC)
    {                           
    
        if (            
            // Detect format insertion markers that are on their own and ignore them, 
            !Regex.IsMatch(m.Value, @"""\s*\{\d(:\d+)?\}\s*""") &&
            //or check for strings of single character length that are not proper characters (-, /, etc)
            !Regex.IsMatch(m.Value, @"""\s*\\?[^\w]\s*""") &&
            //check for digit only strings, allowing for decimal places and an optional percentage or multiplier indicator
            !Regex.IsMatch(m.Value, @"""[\d.]+[%|x]?""") &&
            //check for array indexers
            !(m.Index <= lines[idx].Length && lines[idx][m.Index - 1] == '[' && lines[idx][m.Index + m.Length] == ']')  &&          
            )
        {
            String toCheck = m.Groups[1].Value;
    
            //look up the string we found in our list of constants
            if (constantList.ContainsKey(toCheck))
            {
                String replaceString;
    
                replaceString = "Constants." + constants[toCheck];              
    
                //replace the line in the file
                lines[idx] = lines[idx].Replace("\"" + m.Groups[1].Value + "\"", replaceString);
            }
            else
            {
    
                //See Point 8....
    
            }
        }