在 C# 的属性中使用变量 [英] Using variables within Attributes in C#

查看:36
本文介绍了在 C# 的属性中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一些属性良好的数据库代码,如下所示:

We have some Well-Attributed DB code, like so:

[Display(Name = "Phone Number")]
public string Phone { get; set; }

由于它非常通用,我们想再次使用它,但在属性的名称部分使用不同的字符串.由于它是一个属性,它似乎希望事物是 const,所以我们尝试了:

Since it is quite generic we'd like to use it again, but with a different string in the Name part of the attribute. Since it's an attribute it seems to want things to be const, so we tried:

const string AddressType = "Student ";
[Display(Name = AddressType + "Phone Number")]
public string Phone { get; set; }

这似乎没问题,除了拥有一个 const 字符串意味着我们不能在任何基类中覆盖它,从而删除了我们最初打算添加的功能,并暴露了我的问题:

This seems to work alright, except that having a const string means we can't overwrite it in any base classes, thereby removing the functionality that we originally were intending to add, and exposing my question:

有没有办法在属性内部使用某种变量,以便我们可以继承和保留属性装饰?

Is there a way to use some sort of variable inside of an attribute so that we can inherit and keep the attribute decorations?

推荐答案

编译器必须在编译时知道属性中的所有内容.变量本质上是变量 (!),因此不能在属性中使用.

Everything inside an attribute must be known to the compiler at compile-time. Variables are inherently variable (!) so can't be used in attributes.

如果您可以使用代码生成工具,您就可以将不同的(常量)值动态地注入到每个派生类中.

If you can use a code generation tool, you'd be able to dynamically inject different (constant) values into each derived class.

这篇关于在 C# 的属性中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆