Skip to main content
 首页 » 编程设计

c#之重构常量字符串

2024年02月05日27yjmyzz

我有一些 Item 类,其中包含一个字段

public const string Root = "/homepage"; 

不幸的是,这个字符串不是一个常量!

当我尝试重新定义时

public string Root = DoSomething("/homepage"); 

或属性

public string Root 
{ 
   get { 
      return DoSomething("/homepage"); 
    } 
} 

我被两种不同类型的错误搞得一团糟

A field initializer cannot reference the non-static field, method, or property 'Item.Root' 

还有这个,我认为这可能是一个更大的问题

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type 

如果不进行认真的重构练习,我不太确定如何解决这个问题。有什么建议吗?

请您参考如下方法:

看起来您的代码一直在静态上下文中使用此 const,即来自静态方法或静态属性。这意味着替换属性也必须是 static:

public static string Root = DoSomething("/homepage"); 

当然,这意味着 DoSomething(string) 也必须设为静态。

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

不幸的是,你被困在这里:这个错误无法修复,因为属性参数必须是常量。您需要引用特定属性的文档,看看是否有办法添加“间接级别”,并让属性的用户在运行时执行额外的请求,让您提供计算值。