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

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

问题描述

我们有一些好归于DB code,像这样:

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; }

这似乎好了工作,但有一个常量字符串意味着我们不能在任何基类覆盖它,从而消除我们最初打算添加功能,并揭露我的问题:

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.

如果你可以用code生成工具,你能够动态地注入不同的(常量)值到每个派生类。

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天全站免登陆