【发布时间】:2017-11-30 23:33:05
【问题描述】:
我有一个class,它有一个属性,上面有一个属性:
public class MyClass
{
[CustomAttribute]
public CustomObject Data { get; set; }
}
CustomAttribute 有一个参数,我希望能够在代码中的各个点设置一个编译时常量。
我的问题是:是否可以执行如下所示的操作
public class MyClass
{
// --- Based on the below code, Parameter should be 123
[CustomAttribute(Parameter = HelperAttribute.Value)]
public CustomObject Data { get; set; }
}
// ...
// --- Create a new instance of MyClass, and use the value
// --- 123 for Data's CustomAttribute Parameter.
[HelperAttribute(Value = 123)]
public MyClass Obj { get; set; }
注意:我知道我不能在编译时进行反射部分。我很好奇是否有一种内置于 C# 中的方法。
【问题讨论】:
-
如果您多次使用该属性,编译器如何知道要使用
HelperAttribute.Value的哪个“实例”? -
这是什么栈?您将使用您正在使用的堆栈中的一个功能来传递值(例如,在 Web Api 2 中它是 httpcontext)。
-
@RandomUs1r,基本 C#。
-
@KennethK。编译器真的很聪明是我最好的答案。不过,你确实提出了一个很好的观点。
-
@David Ah 在我头顶上,从未尝试过...看看stackoverflow.com/questions/6637679/… 和stackoverflow.com/questions/6637679/…。注意反思的共同主题,不确定过去。
标签: c# custom-attributes