c# - 从 C# 中的静态数据设置属性名称 property

标签 c#

如何在 C# 中从静态数据设置属性名称属性:

[FaraAuthorize(Roles = RoleValues.SiteManager)] // Error here
public class ProjectsController : FaraController
{
}

public static class RoleValues
{
    static RoleValues()
    {
        using (var db = FaraIdentityEntity.GetEntity())
        {
            SiteManager = db.Roles.Single(item => item.Name == "SiteManager").Id;
        }
    }

    public static string SiteManager = "";
}

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

我可以将 SiteManager 设为 const 字段,但随后我无法在静态构造函数中设置 SiteManager 的值。如何解决这个问题?

最佳答案

基本上你不能。属性值直接嵌入到已编译的程序集中 - 它们无法在执行时确定。如果您需要仅在执行时可用的信息,则需要一种不同的方法,该方法不需要该信息出现在属性值中。

(嗯,您可以使用相关属性数据动态生成类型,但这可能比任何其他方法更难......)

关于c# - 从 C# 中的静态数据设置属性名称 property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30775881/

相关文章:

C# 压缩位图大小而不保存它

c# - DataSet Merge 和 AcceptChanges 以获得 DiffGram

c# - 如何在 JSONP 响应中管理 '?

c# - 我如何记录一个 c# dll

c# - 使用 MongoDB C# 驱动程序从父子层次结构中查找和更新节点

c# - 错误 : ngModel:datefmt Model is not a date object

c# - 如何比较相同的属性值,而不管多个模型中的顺序或重复

c# - 寻找我当前方法调用的 C# 泛型版本

c# - BackgroundWorkers 和 SQL 连接

c# - 在 switch 语句中显示 Console.ReadLine()