我想将下面的 cert 变量设为 const?当我这样做时,我收到一个错误,“分配给 cert 的表达式必须是一个常量”。我在网上看到文章要求将其转换为静态只读而不是 const,并且还说要成为 const,应该在编译时知道该值。
我有两个问题
- cert 不可能是一个 const 变量,因为我不希望它被修改吗?
- 我尝试将 cert 变量设置为只读,这也给了我一个错误,“只读修饰符对此项目无效”。
程序.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IAMAGoodDeveloper
{
public static class Program
{
static void Main(string[] args)
{
programStart();
}
private static void programStart()
{
var myFactory = new MyFactory();
var secretsProvider = myFactory.GenerateKeyProvider();
const int cert = secretsProvider.GetKey("arg");
}
}
}
我的工厂.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IAMAGoodDeveloper
{
public class MyFactory
{
public KeyGen GenerateKeyProvider()
{
return new KeyGen();
}
}
public class KeyGen
{
public int GetKey(string arg)
{
return 1;
}
}
}